C#, Flags Enum, Generic function to look for a flag

后端 未结 11 1576
陌清茗
陌清茗 2020-12-30 05:43

I\'d like one general purpose function that could be used with any Flags style enum to see if a flag exists.

This doesn\'t compile, but if anyone has a suggestion, I

11条回答
  •  庸人自扰
    2020-12-30 06:16

    I have used this before:

    public static bool In(this T me, T values)
        where T : struct, IConvertible
    {
        return (me.ToInt64(null) & values.ToInt64(null)) > 0;
    }
    

    What I like about it is you can use this clean syntax to call it since in 3.5 the compiler will can infer generic parameters.

    AttributeTargets a = AttributeTargets.Class;
    if (a.In(AttributeTargets.Class | AttributeTargets.Module))
    {
       // ...
    }
    

提交回复
热议问题