How do I overload an operator for an enumeration in C#?

后端 未结 5 1026
南旧
南旧 2020-12-06 04:16

I have an enumerated type that I would like to define the >, <, >=, and <= operators for. I know that these o

5条回答
  •  天涯浪人
    2020-12-06 04:23

    According to ECMA-335 Common Language Infrastructure:

    The CTS supports an enum (also known as an enumeration type), an alternate name for an existing type. For the purposes of matching signatures, an enum shall not be the same as the underlying type. Instances of an enum, however, shall be assignable-to the underlying type, and vice versa. That is, no cast (see §8.3.3) or coercion (see §8.3.2) is required to convert from the enum to the underlying type, nor are they required from the underlying type to the enum. An enum is considerably more restricted than a true type, as follows: It shall have exactly one instance field, and the type of that field defines the underlying type of the enumeration.

    • It shall not have any methods of its own.
    • It shall derive from System.Enum (see Partition IV Library – Kernel Package).
    • It shall not implement any interfaces of its own.
    • It shall not have any properties or events of its own.
    • It shall not have any static fields unless they are literal. (see §8.6.1.2)

    Let's assume that we've got following IL code:

    .class public auto ansi sealed Test.Months extends [mscorlib]System.Enum
    {
      .field public specialname rtspecialname int32 value__
      .field public static literal valuetype Test.Months January = int32(0x00000001)
      .field public static literal valuetype Test.Months February = int32(0x00000002)
      .field public static literal valuetype Test.Months March = int32(0x00000003)
      // ...
    
      .method public hidebysig specialname static valuetype Test.Months 
      op_Increment(valuetype Test.Months m) cil managed
      {
        .maxstack 8
    
        IL_0000: ldarg.0
        IL_0001: ldc.i4.s 10
        IL_0003: add
        IL_0004: ret
      }
    } // end of class Test.Months
    

    MSIL compiler (ilasm.exe) will generate following error:

    error -- Method in enum
    ***** FAILURE *****

    So we can't overload enum operator even editing IL code ;)

提交回复
热议问题