我有一个带有Flags属性的枚举.
我的问题是,我想获得所有选项的整数位掩码,而无需自己手动组合所有位.我想这样做以与其他一些int字段进行比较,我希望保护以防未来的开发人员向枚举广告添加更多位选项.
另一件事是我的枚举标志中的位将全部手动分配,所以我不能简单地得到下一个值并减去1.
spi*_*non 21
如果我理解你的问题,这应该对你有用:
Enum.GetValues(typeof(Enum)).Cast<int>().Sum();
Run Code Online (Sandbox Code Playgroud)
然后你可以把它扔回你的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();
}
Run Code Online (Sandbox Code Playgroud)
// 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);
Run Code Online (Sandbox Code Playgroud)
看看我的Unconstrained Melody项目,该项目做了恶事,允许在限制为枚举和委托的泛型方法上构建好的功能.
在这种情况下,我想你想打电话Flags.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);
}
Run Code Online (Sandbox Code Playgroud)