作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在这里,我有一个由位字段指示的主题列表,底部有一个包含可选主题的“可选”字段。
[Flags]
enum Subjects
{
Art = 0b_0000_0001,
Agriculture = 0b_0000_0010,
English = 0b_0000_0100,
Geography = 0b_0000_1000,
Maths = 0b_0001_0000,
Science = 0b_0010_0000,
Optional = Art | Agriculture,
}
Console.WriteLine(Subjects.Optional); // returns "Optional", I expected "Art, Agriculture"
// NOTE: I had to comment out the "Optional" field, otherwise it would return Optional once again
var optional = Subjects.Art | Subjects.Agriculture;
Console.WriteLine(optional); // returns "Art, Agriculture" not "Optional"
最佳答案
您可以按以下方式编写 enum 声明,得到相同的结果:
[Flags]
enum Subjects
{
Art = 0b_0000_0001,
Agriculture = 0b_0000_0010,
English = 0b_0000_0100,
Geography = 0b_0000_1000,
Maths = 0b_0001_0000,
Science = 0b_0010_0000,
Optional = 0b_0000_0011
}
Optional
是组合字段吗?当一个字段存在时,它将在
ToString()
中被选中方法。如果你想避免这种情况,你可以删除
Optional
字段并添加扩展方法:
public bool IsOptional(this Subjects subjects)
{
return subjects.HasFlag(Subjects.Art) && subjects.HasFlag(Subjects.Agriculture);
}
Optional
的另一个值 field
关于c# - 为什么在枚举内声明位域的组合会产生与在枚举外声明不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61722923/
我是一名优秀的程序员,十分优秀!