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

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

    Use Enumerable.Aggregate() to bitwise-or them together. This will work even if you have enum values that represent multiple set bits, as opposed to Sum().

    var myTestValues = (MyTest[]) typeof(MyTest).GetEnumValues();
    var sum = myTestValues.Aggregate((a, b) => a | b);
    sum.Dump();
    

    It's a little tricky to make this generic because you can't constrain generic types to be enums, nor do the primitive types have any subtype relationship to one another. The best I could come up with assumes that the underlying type is int which should be good enough most of the time:

    TEnum AllEnums() 
    {
        var values = typeof(TEnum).GetEnumValues().Cast();
        return (TEnum) (object) values.Aggregate((a,b) => a|b);
    }
    

提交回复
热议问题