标志枚举属性 [英] Flags enum attribute

查看:90
本文介绍了标志枚举属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }

...

var str1 = (Suits.Spades | Suits.Diamonds).ToString();
           // "5"



为什么它是5?我不明白。


Why it is "5"? I don't understand it.

推荐答案

除了解决方案2:



请参阅我的评论问题。属性 System.FlagsAttribute 只影响一件事:枚举值的字符串表示,因此,使用此类表示的所有情况,例如调试器。如果不影响任何其他功能。 Reflection会检查枚举成员的名称并生成位组合名称。如果您想知道这些是如何工作的,可以阅读我的文章枚举类型不枚举!解决.NET和语言限制 [ ^ ]。



-SA
In addition to Solution 2:

Please see my comment to the question. The attribute System.FlagsAttribute affects only one thing: string representation of enumeration values, and, hence, all cases when such representation is used, such as debuggers. If does not affect any other functionality. Reflection examines your enumeration members' name and generates bit-combined names. If you are curious to know how such things work, you can read my article Enumeration Types do not Enumerate! Working around .NET and Language Limitations[^].

—SA


黑桃= 1 dec = 001 bin

钻石= 4 dec = 100 bin



| = 按位或 [ ^ ]



因此:001 bin | 100 bin = 101 bin = 5 dec



或者您可以将其视为向结果添加特定位。这就是为什么标志 [ ^ ]应始终如一定义为2的幂。
Spades = 1 dec = 001 bin
Diamonds = 4 dec = 100 bin

| = bitwise or[^]

hence: 001 bin | 100 bin = 101 bin = 5 dec

Or you can think of it as adding a specific bit to the result. That's why flags[^] should always be defined as powers of 2.


计算机中的数字是二进制的。或符号|正在做001 OR 100 = 101,这是二进制的5。
Numbers in a computer are binary. Or symbol | is doing 001 OR 100 = 101 which is 5 in binary.


这篇关于标志枚举属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆