Why (and how) does the order of an Enum influence the ToString value?

前端 未结 2 1187
北恋
北恋 2021-02-06 04:25

I have problems with the "order" of the values of an enum. It\'s a little difficult to explain, that\'s why I wrote up some code:

class Program
{
    pu         


        
相关标签:
2条回答
  • 2021-02-06 04:59

    The first thing to observe, if you decompile the IL, is that the calls to WriteLine all look remarkably similar:

        L_000c: ldc.i4.1 
        L_000d: box ConsoleApplication2.Program/EnumA
        L_0012: call void [mscorlib]System.Console::WriteLine(object)
        L_0017: nop 
        L_0018: ldc.i4.1 
        L_0019: box ConsoleApplication2.Program/EnumA
        L_001e: call void [mscorlib]System.Console::WriteLine(object)
        L_0023: nop 
        L_0024: ldc.i4.1 
        L_0025: box ConsoleApplication2.Program/EnumA
        L_002a: call void [mscorlib]System.Console::WriteLine(object)
        L_002f: nop 
        L_0030: ldc.i4.4 
        L_0031: box ConsoleApplication2.Program/EnumA
        L_0036: call void [mscorlib]System.Console::WriteLine(object)
        L_003b: nop 
        L_003c: call void [mscorlib]System.Console::WriteLine()
        L_0041: nop 
    

    That is, the loading of these enum values is loading the value "1" three times, and then calling WriteLine. So we should not be surprised that the 1st 3 calls all result in the same value.

    I've tried a few experiments, but can't point to any particular (undocumented) behaviour you can rely on to predict which value will be printed.

    0 讨论(0)
  • 2021-02-06 05:14

    The behaviour is specified to be "undefined" (I thought I'd spotted a pattern just now, but apparently not.) The documentation explicitly calls this out:

    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.

    Either make your enum values distinct, or explicitly create a map from value to desired name.

    0 讨论(0)
提交回复
热议问题