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

前端 未结 2 1185
北恋
北恋 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.

提交回复
热议问题