GetName for enum with duplicate values

后端 未结 5 1640
小鲜肉
小鲜肉 2020-12-07 00:46

If I have duplicate values in a C# enum, saying

enum MyE {
  value1 = 1,
  value2 = 2,
  valued = 1
}

What should be the values of the foll

5条回答
  •  执念已碎
    2020-12-07 01:38

    From the "Remarks" section on the Enum.GetName method documentation (http://msdn.microsoft.com/en-us/library/system.enum.getname.aspx), it says:

    If multiple enumeration members have the same underlying value, the GetName method guarantees that it will return the name of one of those enumeration members. However, it does not guarantee that it will always return the name of the same enumeration member. As a result, when multiple enumeration members have the same value, your application code should never depend on the method returning a particular member's name.

    I ran a test to see what would happen experimentally, and it always returned the first value defined (in your example, value1), but according to the official documentation above, you cannot rely on that (see comment by @gluk47, indicating different behavior in the wild).

提交回复
热议问题