Considering this:
[Flags]
public enum MyEnum {
One = 1,
Two = 2,
Four = 4,
Eight = 8
}
public static class FlagsHelper
{
public static bool Contains(this MyEnum keys, MyEnum flag)
{
return (keys & flag) != 0;
}
}
Is it possible to write a generic version of Contains that would work for any enum
and not just MyEnum
?
Edit:
This would be my version after reading your answers:
public static bool Contains(this Enum keys, Enum flag)
{
ulong keysVal = Convert.ToUInt64(keys);
ulong flagVal = Convert.ToUInt64(flag);
return (keysVal & flagVal) == flagVal;
}
Just realized is a bad idea to check the way I was checking (return (keys & flag) != 0;
), because the flag
parameter might be actually several flags and the common sense thing to do is return true only if keys
contains all of them. Also, I wouldn't check for null values or even make sure they are the same type. I might want to use different types.
question from:
https://stackoverflow.com/questions/4108828/generic-extension-method-to-see-if-an-enum-contains-a-flag 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…