C#如何决定哪个枚举值作为返回值?任何规则
本文关键字:返回值 规则 任何 枚举 何决定 决定 | 更新日期: 2023-09-27 18:24:31
我发现了一个非常有趣的东西----比方说:
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
:
如果多个枚举成员具有相同的基础值,并且尝试检索枚举的字符串表示形式成员的名称基于其基本值,您的代码不应使关于方法将返回哪个名称的任何假设。例如以下枚举定义了两个成员,Shade.Gray和阴影。灰色,具有相同的基本值。
相关:枚举。ToString返回错误的值?
因此,如果你不想依赖这个名称,我会指定唯一的值:
enum Myenum { hello = 1, world = 2, qiang = 3 }