gpt4 book ai didi

c# - 为什么在枚举内声明位域的组合会产生与在枚举外声明不同的结果?

转载 作者:行者123 更新时间:2023-12-03 21:56:10 24 4
gpt4 key购买 nike

在这里,我有一个由位字段指示的主题列表,底部有一个包含可选主题的“可选”字段。

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

现在,如果我要在枚举之外声明相同的 Optional 字段并记录它:
// 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);
}

或者您可以编写自己的方法将您的枚举转换为字符串,也许使用 description attribute获取 Optional 的另一个值 field

关于c# - 为什么在枚举内声明位域的组合会产生与在枚举外声明不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61722923/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com