Neatest way to 'OR' all values in a Flagged Enum?

后端 未结 6 860
伪装坚强ぢ
伪装坚强ぢ 2021-01-17 09:43

Given the enum:

[Flags]
public enum mytest
{
    a = 1,
    b = 2,
    c = 4
}

I\'ve come up with two ways to represent all va

6条回答
  •  攒了一身酷
    2021-01-17 10:12

    It is not as easy as it looks at first sight given the underlying type cast issues:

    static public TEnum GetAllFlags() where TEnum : struct, IComparable, IFormattable, IConvertible
        {
            unchecked
            {
                if (!typeof(TEnum).IsEnum)
                    throw new InvalidOperationException("Can't get flags from non Enum");
                object val = null;
                switch (Type.GetTypeCode(Enum.GetUnderlyingType(typeof(TEnum))))
                {
                    case TypeCode.Byte:
                    case TypeCode.SByte:
                        val = Enum.GetValues(typeof(TEnum))
                                    .Cast()
                                    .Aggregate(default(Byte), ( s, f) => (byte)(s | f));
                        break;
                    case TypeCode.Int16:
                    case TypeCode.UInt16:
                        val = Enum.GetValues(typeof(TEnum))
                                    .Cast()
                                    .Aggregate(default(UInt16), ( s, f) => (UInt16)(s | f));
                        break;
                    case TypeCode.Int32:
                    case TypeCode.UInt32:
                        val = Enum.GetValues(typeof(TEnum))
                                    .Cast()
                                    .Aggregate(default(UInt32), ( s, f) => (UInt32)(s | f));
                        break;
                    case TypeCode.Int64:
                    case TypeCode.UInt64:
                        val = Enum.GetValues(typeof(TEnum))
                                    .Cast()
                                    .Aggregate(default(UInt64), ( s, f) => (UInt64)(s | f));
                        break;
                    default :
                        throw new InvalidOperationException("unhandled enum underlying type");
    
                }
                return (TEnum)Enum.ToObject(typeof(TEnum), val);
            }
        }
    

    More about this kind of conversions can be found here

提交回复
热议问题