加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 正确识别具有相同基础值的枚举

发布时间:2020-12-15 08:18:22 所属栏目:百科 来源:网络整理
导读:假设我定义了这个枚举,其中有几个成员具有相同的基础值: enum Number{ One = 1,Eins = 1,Uno = 1} 根据MSDN documentation: If multiple enumeration members have the same underlying value and you attempt to retrieve the string representation of a
假设我定义了这个枚举,其中有几个成员具有相同的基础值:
enum Number
{
  One = 1,Eins = 1,Uno = 1
}

根据MSDN documentation:

If multiple enumeration members have the same underlying value and you attempt to retrieve the string representation of an enumeration member’s name based on its underlying value,your code should not make any assumptions about which name the method will return.

所以,例如,

var number = Number.One;
Console.WriteLine(number);

给我以下输出:

Eins

打印所有枚举成员,

Console.WriteLine($"{Number.One} {Number.Eins} {Number.Uno}");

产生以下输出:

Eins Eins Eins

但是,取每个成员的名字,

Console.WriteLine($"{nameof(Number.One)} {nameof(Number.Eins)} {nameof(Number.Uno)}");

给出以下结果:

One Eins Uno

显然,枚举成员是可分离的.我可以利用这种分离,即有什么方法可以将特定的Number成员分配给变量,并且每当访问变量时都会返回相同的成员吗?

解决方法

So apparently the enum members are separable

嗯,这不完全正确……它们只能在编译时分离.

你看,nameof实际上是一个在编译时评估的表达式.这是一个不变的表达.这可以通过为const指定一个表达式来证明:

const string a = nameof(Number.One);

它汇编.

另一方面,尝试使用字符串插值获取枚举值的字符串表示形式,在运行时进行评估,因此不会编译:

const string a = $"{Number.One}";

在运行时,枚举案例是不可分的,所以答案是:

is there any way I can assign a specific Number member to a variable and consistently have that same member returned whenever the variable is accessed?

没有”.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读