Enum.HasFlag, why no Enum.SetFlag?

前端 未结 8 2101
别跟我提以往
别跟我提以往 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:15

    Here is another quick and dirty way to SetFlag for any Enum:

    public static T SetFlag(this T flags, T flag, bool value) where T : struct, IComparable, IFormattable, IConvertible
        {
            int flagsInt = flags.ToInt32(NumberFormatInfo.CurrentInfo);
            int flagInt = flag.ToInt32(NumberFormatInfo.CurrentInfo);
            if (value)
            {
                flagsInt |= flagInt;
            }
            else
            {
                flagsInt &= ~flagInt;
            }
            return (T)(Object)flagsInt;
        }
    

提交回复
热议问题