Extending an enum via inheritance

后端 未结 15 2562
温柔的废话
温柔的废话 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:31

    The reason you can't extend Enums is because it would lead to problems with polymorphism.

    Say you have an enum MyEnum with values A, B, and C , and extend it with value D as MyExtEnum.

    Suppose a method expects a myEnum value somewhere, for instance as a parameter. It should be legal to supply a MyExtEnum value, because it's a subtype, but now what are you going to do when it turns out the value is D?

    To eliminate this problem, extending enums is illegal

提交回复
热议问题