Gre*_*arr 2 .net c# enums bit-manipulation .net-3.5
我知道在.NET 4中你可以使用HasFlag
在.NET 3.5中有以下任何替代方法吗?
if ((enumVar & EnumType.ValueOne) == EnumType.ValueOne)
{
// someMethod(1) or someMethod(EnumType.ValueOne)
}
if ((enumVar & EnumType.ValueTwo) == EnumType.ValueTwo)
{
// someMethod(2) or someMethod(EnumType.ValueTwo)
}
if ((enumVar & EnumType.ValueThree) == EnumType.ValueThree)
{
// someMethod(3) or someMethod(EnumType.ValueThree)
}
if ((enumVar & EnumType.ValueFour) == EnumType.ValueFour)
{
// someMethod(4) or someMethod(EnumType.ValueFour)
}
Run Code Online (Sandbox Code Playgroud)
枚举中每个值的...等等?您必须能够使用for..each循环来完成此操作,其中someMethod的参数是循环的索引?
[Flags]
enum EnumType
{
ValueOne = 1
, ValueTwo = 2
, ValueThree = 4
, ValueFour = 8
}
Run Code Online (Sandbox Code Playgroud)
编辑:只有值得查看接受的答案,其余的评论/答案可以安全地忽略.
你应该可以写这样的东西.你可以根据需要使它成为通用的,但是没有办法将约束设置为枚举,所以你必须用反射检查自己.
public static bool HasFlag(YourEnum source, YourEnum flag)
{
return (source & flag) == flag;
}
Run Code Online (Sandbox Code Playgroud)