我有一个带有Flags属性的枚举。
我的问题是,我想获取所有选项的整数位掩码,而不是手动将所有位组合起来。我想这样做是为了与某些其他int字段进行比较,并且我想保护代码以防未来的开发人员向枚举中添加更多位选项。
另一件事是,我的枚举标志中的位都是手动分配的,因此我不能简单地获取下一个值并减去1。
如果我正确理解了您的问题,那么这个方法应该适合您:
Enum.GetValues(typeof(Enum)).Cast<int>().Sum();
您随后可以将其转换回 typeof(Enum)
类型:
[Flags]
public enum Values
{
Value_1 = 1,
Value_2 = 2,
Value_3 = 4,
Value_4 = 8,
Value_5 = 16,
Value_6 = 32,
Value_7 = 64,
Value_8 = 128,
Value_9 = 256
}
static void Main(string[] args)
{
Values values = (Values)Enum.GetValues(typeof(Values)).Cast<int>().Sum();
}
// uses a ulong to handle all possible underlying types without error
var allFlags = Enum.GetValues(typeof(YourEnumType))
.Cast<YourEnumType>()
.Aggregate((YourEnumType)0, (a, x) => a | x, a => (ulong)a);
ulong
类型,以便它可以处理所有可能的基础类型。(我已经将其强制转换而不是保留为YourEnumType
,因为OP要求一个整数位掩码。) - LukeHFlags.GetUsedBits<YourEnumType>()
。[Flags]
enum SomeFlags
{
Flag1 = 1,
Flag2 = 2,
Flag3 = 4,
Flag4 = 16,
Flag5 = 32,
Flag6 = 64
}
static void Main(string[] args)
{
SomeFlags flags = 0;
SomeFlags[] values = (SomeFlags[])Enum.GetValues(typeof(SomeFlags));
Array.ForEach<SomeFlags>(values, delegate(SomeFlags v) { flags |= v; });
int bitMask = Convert.ToInt32(flags);
}
这里有一种方法可以实现,使用 Jon Skeet 和 Marc Gravell 编写的 通用运算符 的思路:
void Main()
{
Console.WriteLine(CombineAllFlags<MyEnum>()); // Prints "Foo, Bar, Baz"
}
[Flags]
public enum MyEnum
{
Foo = 1,
Bar = 2,
Baz = 4
}
public static TEnum CombineAllFlags<TEnum>()
{
TEnum[] values = (TEnum[])Enum.GetValues(typeof(TEnum));
TEnum tmp = default(TEnum);
foreach (TEnum v in values)
{
tmp = EnumHelper<TEnum>.Or(tmp, v);
}
return tmp;
}
static class EnumHelper<T>
{
private static Func<T, T, T> _orOperator = MakeOrOperator();
private static Func<T, T, T> MakeOrOperator()
{
Type underlyingType = Enum.GetUnderlyingType(typeof(T));
ParameterExpression xParam = Expression.Parameter(typeof(T), "x");
ParameterExpression yParam = Expression.Parameter(typeof(T), "y");
var expr =
Expression.Lambda<Func<T, T, T>>(
Expression.Convert(
Expression.Or(
Expression.Convert(xParam, underlyingType),
Expression.Convert(yParam, underlyingType)),
typeof(T)),
xParam,
yParam);
return expr.Compile();
}
public static T Or(T x, T y)
{
return _orOperator(x, y);
}
}