如果枚举值相同,我将获得哪个枚举常数 [英] Which Enum constant will I get if the Enum values are same

查看:131
本文介绍了如果枚举值相同,我将获得哪个枚举常数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有不止一个具有相同值的枚举常数,是否有一个常量?



我尝试了以下变体,



主要方法:



  public class程序
{
public static void Main(string [] args)
{
测试a = 0;
Console.WriteLine(a);
}
}



首先尝试:



 枚举测试
{
a1 = 0,
a2 = 0,
a3 = 0,
a4 = 0,
}

输出:

  a2 



第二次尝试: test
{
a1 = 0,
a2 = 0,
a3 ,
a4 = 0,
}

输出:

  a4 



第三测试

a1 = 0,
a2 = 0,
a3,
a4,
}

输出:

  a2 



第四尝试:



 枚举测试
{
a1 = 0,
a2 = 0 ,
a3,
a4
}

输出: p>

  a1 


解决方案

文档实际上解决了这一点:


如果多个枚举成员具有相同的底层值,并尝试根据其基础值检索枚举成员名称的字符串表示形式,您的代码不应该


(加重点)



但是,这并不意味着结果是随机。这意味着它是一个可以更改的实现细节。实现可以通过修补程序完全改变,在编译器(MONO,Roslyn等)上可能会有所不同,并且在不同的平台上是不同的。



如果您的系统设计为需要,枚举的反向查找在时间和平台上是一致的,那么<使用 Enum.ToString 。要么改变你的设计,所以它不依赖于这个细节,或者写出你自己的 方法是一致的。



所以你不应该编写依赖于这个实现的代码,否则你将面临一个风险,在将来的版本中你不会有所改变。


Is there a logic to which constant I get if there are more than one enum constant that has the same value?

I tried the variations below, but couldn't get a reasonable logic.

Main Method:

public class Program
{
    public static void Main(string[] args)
    {
        Test a = 0;
        Console.WriteLine(a);
    }
}

First try:

enum Test
{
    a1=0,
    a2=0,
    a3=0,
    a4=0,
}

Output:

a2

Second try:

enum Test
{
    a1=0,
    a2=0,
    a3,
    a4=0,
}

Output:

a4

Third try:

enum Test
{
    a1=0,
    a2=0,
    a3,
    a4,
}

Output:

a2

Fourth try:

enum Test
{
    a1=0,
    a2=0,
    a3,
    a4
}

Output:

a1

解决方案

The documentation actually addresses this:

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.

(emphasis added)

However, this does not mean that the result is random. What that means it that it's an implementation detail that is subject to change. The implementation could completely change with just a patch, could be different across compilers (MONO, Roslyn, etc.), and be different on different platforms.

If your system is designed that it requires that the reverse-lookup for enums is consistent over time and platforms, then don't use Enum.ToString. Either change your design so it's not dependent on that detail, or write your own method that will be consistent.

So you should not write code that depends on that implementation, or you are taking a risk that it will change without your knowledge in a future release.

这篇关于如果枚举值相同,我将获得哪个枚举常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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