Enum.HasFlag, why no Enum.SetFlag?

前端 未结 8 2033
别跟我提以往
别跟我提以往 2020-12-24 05:38

I have to build an extension method for each flag type I declare, like so:

public static EventMessageScope SetFlag(this EventMessageScope flags, 
    EventMe         


        
相关标签:
8条回答
  • 2020-12-24 06:32

    Enums got borked by the C language a long time ago. Having a modicum of type safety in the C# language was important to the designers, leaving no room for an Enum.SetFlags when the underlying type can be anything between a byte and a long. Another C induced problem btw.

    The proper way to deal with it is to write this kind of code inline explicitly and not try to shove it into an extension method. You don't want to write a C macro in the C# language.

    0 讨论(0)
  • 2020-12-24 06:35

    Why isn't there an Enum.SetFlag like there is an Enum.HasFlag?

    HasFlag as a bitwise operation required more complicated logic and repeating the same flag twice

     myFlagsVariable=    ((myFlagsVariable & MyFlagsEnum.MyFlag) ==MyFlagsEnum.MyFlag );
    

    so MS decided to implement it.

    SetFlag and ClearFlag are concise in C#

        flags |= flag;// SetFlag
    
        flags &= ~flag; // ClearFlag 
    

    but unfortunately not intuitive. Every time I need to set (or clear) a flag, I'm spending a few seconds (or minutes) to think: what is the name of the method? Why is it not shown in intellisense? Or no, I have to use bitwise operations. Note, that some developers will also ask: what is a bitwise operation?

    Should SetFlag and ClearFlag extensions be created - YES to appear in intellisense.

    Should SetFlag and ClearFlag extensions be used by developers - NO, because they are not efficient.

    We've created extensions in our library's class EnumFlagsHelper like in SomeEnumHelperMethodsThatMakeDoingWhatYouWantEasier, but named the function as SetFlag instead of Include and ClearFlag instead of Remove.

    In the body of SetFlag methods ( and in summary comment) I decided to add

    Debug.Assert( false, " do not use the extension due to performance reason, use bitwise operation with the explanatory comment instead \n 
    flags |= flag;// SetFlag")
    

    and a similar message should be added to ClearFlag

    Debug.Assert( false, " do not use the extension due to performance reason, use bitwise operation with the explanatory comment instead \n 
             flags &= ~flag; // ClearFlag  ")
    
    0 讨论(0)
提交回复
热议问题