Generic extension method to see if an enum contains a flag

前端 未结 8 1099
闹比i
闹比i 2021-02-01 01:56

Considering this:

[Flags]
public enum MyEnum {
    One = 1,
    Two = 2,
    Four = 4,
    Eight = 8
}

public static class FlagsHelper
{
    public static bool          


        
8条回答
  •  粉色の甜心
    2021-02-01 02:40

    Unfortunately no there is not a good way to make an extension method like this. In order for this to work you'd need to have a generic method which operated on enum values. Unfortunately there is no way to constrain generic arguments to be an enum

    // Ilegal
    public static bool Contains(this T value, T flag) where T : enum {
      ...
    }
    

    The best I've come up with is the following

    public static bool HasFlag(this System.Enum e, T flag) 
    {
        var intValue = (int)(object)e;
        var intFlag = (int)(object)flag;
        return (intValue & intFlag) != 0;
    }
    

    However it's limited in several ways

    • Not type safe because there is no requirement the value and the flag have the same type
    • Assumes that all enum values are int based.
    • Causes boxing to occur for a simple bit check
    • Will throw if e is null

提交回复
热议问题