问题描述
考虑到这一点:
[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;
}
}
是否有可能包含了写一个通用版本将适用于任何枚举
而不仅仅是 MyEnum
?
Is it possible to write a generic version of Contains that would work for any enum
and not just MyEnum
?
修改
这将是我的版本阅读你的答案后:
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;
}
刚刚意识到是一个坏主意来检查我检查的方式(收益率(键和放大器;标志)!= 0;
),因为标志
参数可能是实际上的几个标志和常识要做的事情就是返回true,只有当键
包含了所有的人。另外,我也不会检查空值,甚至以确保它们是同一类型。我可能的希望的使用不同类型。
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.
推荐答案
我根据这个方法一串,这样的&安培;谷歌搜索,以及通过使用反射器,看看有什么MS所做的.NET 4 HasFlags方法。
I based this method off of a bunch of SO & Google searches, and a by using reflector to see what MS did for the .NET 4 HasFlags method.
public static class EnumExt
{
/// <summary>
/// Check to see if a flags enumeration has a specific flag set.
/// </summary>
/// <param name="variable">Flags enumeration to check</param>
/// <param name="value">Flag to check for</param>
/// <returns></returns>
public static bool HasFlag(this Enum variable, Enum value)
{
if (variable == null)
return false;
if (value == null)
throw new ArgumentNullException("value");
// Not as good as the .NET 4 version of this function, but should be good enough
if (!Enum.IsDefined(variable.GetType(), value))
{
throw new ArgumentException(string.Format(
"Enumeration type mismatch. The flag is of type '{0}', was expecting '{1}'.",
value.GetType(), variable.GetType()));
}
ulong num = Convert.ToUInt64(value);
return ((Convert.ToUInt64(variable) & num) == num);
}
}
注:
Notes:
- 此处理空值
- 请问类型检查
- 转换为ULONG,并且可以处理任何积极的枚举值。 反对使用负标志枚举反正:
- This handles nulls
- Does type checking
- Converts to a ulong, and can handle any positive enum value. Microsoft cautions against the use of negative flags enumerations anyway:
如果你定义一个负数的枚举常量,因为许多标记位置可能被设置为1的标志,这可能使你的代码混乱和鼓励编码错误要小心。
这篇关于看看通用扩展方法,如果枚举包含一个标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!