What determines which name is selected when calling ToString() on an enum value which has multiple corresponding names?

后端 未结 3 747
生来不讨喜
生来不讨喜 2021-02-13 06:10

What determines which name is selected when calling ToString() on an enum value which has multiple corresponding names?

Long explanation

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-13 06:11

    I might be going too far here, but I think it's decided by binary search of the sorted values, and so can depend on the parity of the total number of values. You can illustrate this with your last example (RgbColorWithAFirst and RgbColorWithALast) by defining another value in both - then you get A from all the ToString invocations.

    I got here by decompiling mscorlib (4.0) and noting that eventually we get to a call to Array.BinarySearch on a sorted array of the declared values. Naturally, the binary search stops as soon as it gets a match, so to get it to switch between two identical values the easiest way is to alter the search tree, by adding an extra value.

    Of course, this is an implementation detail and should not be relied on. It seems to me that in your case you would be best served by using DescriptionAttribute on enum values where you want to be explicit about the display value, and a helper method such as:

    public static class EnumExtensions
    {
        public static string Description(this Enum value)
        {
            var field = value.GetType().GetField(value.ToString());
            var attribute = Attribute.GetCustomAttribute(
                                field, 
                                typeof (DescriptionAttribute)) 
                            as DescriptionAttribute;
    
            return attribute == null ? value.ToString() : attribute.Description;
        }
    }
    

提交回复
热议问题