C#如何确定哪个枚举值作为返回值?任何规则? [英] How does C# decide which enum value as a returned one? Any rules?

查看:294
本文介绍了C#如何确定哪个枚举值作为返回值?任何规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现一个非常有趣的事情 - 让我们说:

I found a very intersting thing——Let's say:

 enum Myenum { a, b, c= 0 }
    public class Program
    {
        static void Main(string[] args)
        {
            Myenum ma = Myenum.a;
            Console.WriteLine(ma);
        }
    }

结果是 a ,为什么?

如果我说:

 enum Myenum { a, b=0, c}
    public class Program
    {
        static void Main(string[] args)
        {
            Myenum ma = Myenum.a;
            Console.WriteLine(ma);
        }
    }

结果变成b,为什么?

推荐答案

Enum.ToString


如果多个枚举成员具有相同的底层值,并且
尝试根据其底层值检索枚举
成员名称的字符串表示形式, strong>你的代码不应该使
任何关于该方法将返回的名称的假设。例如,
,以下枚举定义了两个成员Shade.Gray和
Shade.Grey,具有相同的底层值。

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. For example, the following enumeration defines two members, Shade.Gray and Shade.Grey, that have the same underlying value.

相关: enum.ToString返回错误的值?

所以如果你不依赖这个名字,我会分配唯一的值:

So i would assign unique values if you wannt to rely on the name:

enum Myenum { hello = 1, world = 2, qiang = 3 }

这篇关于C#如何确定哪个枚举值作为返回值?任何规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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