如何在 C# 中重写枚举?
这是我的代码:
void Main()
{
StarTrek baseClass = new StarTrek();
NewGeneration childClass = new NewGeneration();
baseClass.ShowEnum();
childClass.ShowEnum();
}
public class StarTrek
{
internal enum Characters
{
Kirk, Spock, Sulu, Scott
}
public void ShowEnum()
{
Type reflectedEnum = typeof(Characters);
IEnumerable<string> members = reflectedEnum.GetFields()
.ToList()
.Where(item => item.IsSpecialName == false)
.Select(item => item.Name);
string.Join(", ", members).Dump();
}
}
public class NewGeneration : StarTrek
{
internal new enum Characters
{
Picard, Riker, Worf, Geordi
}
}
ShowEnum 始终显示:
柯克、斯波克、苏鲁、斯科特
即使是在NewGeneration班上叫的。我错过/误解了什么吗? ShowEnum 有没有办法使用 NewGeneration.Characters 而不是 StarTrek.Characters?
This is my code:
void Main()
{
StarTrek baseClass = new StarTrek();
NewGeneration childClass = new NewGeneration();
baseClass.ShowEnum();
childClass.ShowEnum();
}
public class StarTrek
{
internal enum Characters
{
Kirk, Spock, Sulu, Scott
}
public void ShowEnum()
{
Type reflectedEnum = typeof(Characters);
IEnumerable<string> members = reflectedEnum.GetFields()
.ToList()
.Where(item => item.IsSpecialName == false)
.Select(item => item.Name);
string.Join(", ", members).Dump();
}
}
public class NewGeneration : StarTrek
{
internal new enum Characters
{
Picard, Riker, Worf, Geordi
}
}
ShowEnum always displays:
Kirk, Spock, Sulu, Scott
even if it was called in the NewGeneration class. Am I missing/misunderstanding something? Is there a way for ShowEnum to use the NewGeneration.Characters instead of StarTrek.Characters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的第二个枚举遮盖第一个枚举,就像在
NewGeneration
中声明新字段一样。嵌套类型不是多态的 - ShowEnum 中的代码将始终引用StarTrek.Characters
;代码是在编译时针对该类型构建的。目前还不清楚你想要做什么,但你绝对不能按照你正在尝试的方式去做。如果您想要多态行为,您必须使用方法、属性或事件,然后必须将它们声明为虚拟,以便在派生类中重写。
(值得注意的是,重载和重写是不同的,顺便说一句 - 你的问题是指重载,但我认为你的意思是重写。)
Your second enum is shadowing the first one, in just the same way as declaring a new field within
NewGeneration
would. Nested types aren't polymorphic - the code inShowEnum
will always refer toStarTrek.Characters
; the code is built against that type at compile-time.It's not really clear what you're trying to do, but you definitely can't do it in the way that you're trying. If you want polymorphic behaviour you have to be using methods, properties or events, which must then be declared virtual in order to be overridden in the derived class.
(It's worth noting that overloading and overriding are different, by the way - your question refers to overloading but I think you meant overriding.)
您不能重载
enum
- 它们不是类或结构。使用
internal new
,您只是隐藏原始属性,因为您ShowEnum
是在基类上定义的,所以基类实现该属性称为。You can't overload
enum
s - they are not classes or structs.With
internal new
you are simply hiding the original property, though, since you areShowEnum
is defined on the base class, the base class implementation of the property is called.