Using an enum having entries with the same value of underlying type

后端 未结 3 747
遇见更好的自我
遇见更好的自我 2021-01-16 17:28

if i declare an enum like

enum Weekdays
{
    Mon = 1,
    Tue = 1,
    Wen = 1,
    Thi,
    Fri,
    Sat,
    Sun
}

Weekdays obj = (Weekdays)1;
Console.Wr         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-16 18:32

    When you write out your value like this, it ends up getting ToString() called on it.

    Console.WriteLine(obj);
    

    If you dig into the code far enough down, it's calling Enum.GetName() on your value.

    Regarding multiple enum values with the same underlying value, the Enum.GetName page on MSDN 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.

    It doesn't state how it determines which name to return if the values on two or more are the same.

    The docs for Enum.ToString() include the same warning, in slightly different wording.

    Digging a little deeper, the method above makes a call to Array.BinarySearch, passing it an array of numbers representing all values in your enum, and a number representing the value you want to print.

    So you have an array with multiple 1's in it, and you're searching for a 1. The docs for that call are similar:

    Duplicate elements are allowed. If the Array contains more than one element equal to value, the method returns the index of only one of the occurrences, and not necessarily the first one.

    Again, it doesn't state how a selection is made, just that it'll be unreliable.

提交回复
热议问题