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

后端 未结 6 897
伪装坚强ぢ
伪装坚强ぢ 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:03

    For a generic method, use Linq's Enumerable.Aggregate extension method;

    var flags = Enum.GetValues(typeof(mytest))
                    .Cast()
                    .Aggregate(0, (s, f) => s | f);
    

    Or in a wrapper method

    TEnum GetAll() where TEnum : struct
    {
        return (TEnum) (object)
                Enum.GetValues(typeof(TEnum))
                    .Cast()
                    .Aggregate(0, (s, f) => s | f);
    }
    

    full credit for this double-cast trick goes to @millimoose

提交回复
热议问题