Extending an enum via inheritance

后端 未结 15 2545
温柔的废话
温柔的废话 2020-11-27 17:40

I know this rather goes against the idea of enums, but is it possible to extend enums in C#/Java? I mean \"extend\" in both the sense of adding new values to an enum, but a

15条回答
  •  日久生厌
    2020-11-27 18:25

    You're going the wrong way: a subclass of an enum would have fewer entries.

    In pseudocode, think:

    enum Animal { Mosquito, Dog, Cat };
    enum Mammal : Animal { Dog, Cat };  // (not valid C#)
    

    Any method that can accept an Animal should be able to accept a Mammal, but not the other way around. Subclassing is for making something more specific, not more general. That's why "object" is the root of the class hierarchy. Likewise, if enums were inheritable, then a hypothetical root of the enum hierarchy would have every possible symbol.

    But no, C#/Java don't allow sub-enums, AFAICT, though it would be really useful at times. It's probably because they chose to implement Enums as ints (like C) instead of interned symbols (like Lisp). (Above, what does (Animal)1 represent, and what does (Mammal)1 represent, and are they the same value?)

    You could write your own enum-like class (with a different name) that provided this, though. With C# attributes it might even look kind of nice.

提交回复
热议问题