定义一个枚举为2的标志/权力,而不是最终需要一个计算器的任何伎俩?

我知道我可以繁殖,但我是不想做懒惰编程。

有没有人devise一些巫术来自动枚举两个幂的枚举?

以下是我只是想具体说明的例子:

[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 } 

将值写入移位位,并让编译器进行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. } 

詹姆斯的build议也是一个很好的build议。 事实上,我更喜欢这种方式。 你也可以这样写:

 [Flags] private enum Targets : uint { None = 0, Campaigns = 1 << 0, CampaignGroups = 1 << 1, Advertisers = 1 << 2, AdvertiserGroups = 1 << 3, AffiliateGroups = 1 << 4, // etc. } 

使用hex符号比小数符号简单一点(不需要计算器):

 [Flags] private enum Targets : uint { None = 0, Campaigns = 0x01, CampaignGroups = 0x02, Advertisers = 0x04, AdvertiserGroups = 0x08, AffiliateGroups = 0x10, Affiliates = 0x20, Creatives = 0x40, DetailedLeads = 0x80, DetailedSales = 0x100, ProgramLeads = 0x200, CreativeDeployments = 0x400, CampaignCategories = 0x800, Payouts = 0x1000, // and the pattern of doubling continues // 0x2000 // 0x4000 // 0x8000 // 0x10000 } 

不像科迪和詹姆斯的解决scheme一样优雅,但不需要计算器。

快进未来的五年,从C#7.0开始,您可以使用新的数字二进制文字来简化枚举标志声明。

 [Flags] private enum Targets : uint { None = 0, Campaigns = 0b0000_0000_0000_0001, CampaignGroups = 0b0000_0000_0000_0010, Advertisers = 0b0000_0000_0000_0100, AdvertiserGroups = 0b0000_0000_0000_1000, AffiliateGroups = 0b0000_0000_0001_0000, Affiliates = 0b0000_0000_0010_0000, Creatives = 0b0000_0000_0100_0000, DetailedLeads = 0b0000_0000_1000_0000, DetailedSales = 0b0000_0001_0000_0000, ProgramLeads = 0b0000_0010_0000_0000, CreativeDeployments = 0b0000_0100_0000_0000, CampaignCategories = 0b0000_1000_0000_0000, Payouts = 0b0001_0000_0000_0000, All = uint.MaxValue } 

https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#numeric-literal-syntax-improvements