Enum.HasFlag, why no Enum.SetFlag?

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

    I've done something that works for me and that's very simple...

        public static T SetFlag(this Enum value, T flag, bool set)
        {
            Type underlyingType = Enum.GetUnderlyingType(value.GetType());
    
            // note: AsInt mean: math integer vs enum (not the c# int type)
            dynamic valueAsInt = Convert.ChangeType(value, underlyingType);
            dynamic flagAsInt = Convert.ChangeType(flag, underlyingType);
            if (set)
            {
                valueAsInt |= flagAsInt;
            }
            else
            {
                valueAsInt &= ~flagAsInt;
            }
    
            return (T)valueAsInt;
        }
    

    Usage:

        var fa = FileAttributes.Normal;
        fa = fa.SetFlag(FileAttributes.Hidden, true);
    

提交回复
热议问题