在最终不需要计算器的情况下将枚举定义为 2 的标志/幂的任何技巧? [英] Any trick to defining an enum as flags/powers of 2 without eventually needing a calculator?
本文介绍了在最终不需要计算器的情况下将枚举定义为 2 的标志/幂的任何技巧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道我可以乘法但我不想做懒惰的编程.
I know I can multiply but being the lazy programming I am I do not want to.
有没有人设计了一些魔法来将枚举自动编号为 2 的幂?
Has anyone devised some sorcery to auto number the enums as powers of two?
下面是我为了让它具体化的例子:
Here's the example I have just to make it concrete:
[Flags]
private enum Targets : uint
{
None = 0,
Campaigns = 1,
CampaignGroups = 2,
Advertisers = 4,
AdvertiserGroups = 8,
AffiliateGroups = 16,
Affiliates = 32,
Creatives = 64,
DetailedLeads = 128,
DetailedSales = 256,
ProgramLeads = 512,
CreativeDeployments = 1024,
CampaignCategories = 2048,
Payouts = 4096,
All = uint.MaxValue
}
推荐答案
将值写为移位的位并让编译器进行数学运算:
Write the values as shifted bits and let the compiler do the math:
[Flags]
private enum Targets : uint
{
None = 0,
Campaigns = 1,
CampaignGroups = 2 << 0,
Advertisers = 2 << 1,
AdvertiserGroups = 2 << 2,
AffiliateGroups = 2 << 3,
Affiliates = 2 << 4,
Creatives = 2 << 5,
DetailedLeads = 2 << 6,
DetailedSales = 2 << 7,
ProgramLeads = 2 << 8,
CreativeDeployments = 2 << 9,
CampaignCategories = 2 << 10,
Payouts = 2 << 11,
// etc.
}
James 的建议也不错.事实上,我更喜欢这种方式.你也可以这样写:
James's suggestion is a good one, too. In fact I like this way even better. You could also write it like this:
[Flags]
private enum Targets : uint
{
None = 0,
Campaigns = 1 << 0,
CampaignGroups = 1 << 1,
Advertisers = 1 << 2,
AdvertiserGroups = 1 << 3,
AffiliateGroups = 1 << 4,
// etc.
}
这篇关于在最终不需要计算器的情况下将枚举定义为 2 的标志/幂的任何技巧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文