扩展通过继承枚举 [英] Extending an enum via inheritance

查看:217
本文介绍了扩展通过继承枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这相当不利于枚举的想法,但有可能延长枚举在C#/ Java的?在增加新的价值,以枚举双方的意义上,我的意思是扩展,而且在从现有的枚举继承的面向对象的意义。

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 also in the OO sense of inheriting from an existing enum.

我想这是不可能在Java中,因为它仅得到了他们相当最近(Java 5的?)。 C#似乎更宽容的人希望做疯狂的事情,虽然如此,我认为这是可能的一些方法。 presumably它可以通过反射被黑客攻击了(不是说你所有的实际使用该方法)?

I assume it's not possible in Java, as it only got them fairly recently (Java 5?). C# seems more forgiving of people that want to do crazy things, though, so I thought it might be possible some way. Presumably it could be hacked up via reflection (not that you'd every actually use that method)?

我并不感兴趣,在实施任何给定的方法,它只是受到挑衅时,我想到了我的好奇: - )

I'm not necessarily interested in implementing any given method, it just provoked my curiosity when it occurred to me :-)

推荐答案

您不能扩展枚举的原因是因为它会导致问题的多态性。

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

假设你有一个枚举MyEnum与值A,B和C,并与值D为MyExtEnum扩展它。

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

假设一个方法需要一个myEnum价值的地方,例如作为一个参数。它应该是合法的供应MyExtEnum的价值,因为它是一个亚型,但现在你有什么打算这样做,当它原来的价值为D?

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

这篇关于扩展通过继承枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆