C# 调用重写的子类方法而不知道它是子类实例
我有一个带有虚拟方法的基类,以及多个重写该方法的子类。
当我遇到这些子类之一时,我想调用重写的方法,但不知道子类。 我可以想到一些丑陋的方法来做到这一点(检查一个值并转换它),但似乎应该有一种语言内的方法来做到这一点。 我希望列表在同一个列表中包含多个子类,否则显然我可以创建一个列表。
编辑:修复了代码中错误的注释,这导致了我得到的非常合适的第一个答案:)
例如:
Class Foo
{
public virtual printMe()
{
Console.Writeline("FOO");
}
}
Class Bar : Foo
{
public override printMe()
{
Console.Writeline("BAR");
}
}
List<Foo> list = new List<Foo>();
// then populate this list with various 'Bar' and other overriden Foos
foreach (Foo foo in list)
{
foo.printMe(); // prints FOO.. Would like it to print BAR
}
I have a base class with a virtual method, and multiple subclasses that override that method.
When I encounter one of those subclasses, I would like to call the overridden method, but without knowledge of the subclass. I can think of ugly ways to do this (check a value and cast it), but it seems like there should be an in-language way to do it. I want the List to contain multiple subclasses within the same list, otherwise obviously I could just make a List.
EDIT: Fixed the comment in the code that was wrong, which lead to the very appropriate first answer I got :)
For instance:
Class Foo
{
public virtual printMe()
{
Console.Writeline("FOO");
}
}
Class Bar : Foo
{
public override printMe()
{
Console.Writeline("BAR");
}
}
List<Foo> list = new List<Foo>();
// then populate this list with various 'Bar' and other overriden Foos
foreach (Foo foo in list)
{
foo.printMe(); // prints FOO.. Would like it to print BAR
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为什么要打印“Foo”? 这不是虚拟方法的目的。 重点是派生类可以在不改变接口的情况下改变函数的工作方式。 Foo 对象将打印“Foo”,Bar 对象将打印“Bar”。 其他任何事情都会是错误的。
Why should it print "Foo"? That is not the purpose of virtual methods. The whole point is that the derived classes can change the way the function works without changing the interface. A Foo object will print "Foo" and a Bar object will print "Bar". Anything else would be wrong.
要在这种情况下获得您想要的行为,您可以删除基类上的 virtual 并在子类上使用 new 。
然而,正如埃德·斯旺格伦(Ed Swangren)指出的那样,你为什么要这么做呢?
To get the behavior you want in this situation you could remove the virtual on the base class and use new on the subclass.
However, like Ed Swangren indicated, why would you?
是否没有一种解决方案,您只需将要调用的对象转换为另一个对象:
成为
或者我错过了问题的某些部分?
Isn't there a solution where you just cast the object you want to call the other one:
becomes
Or am I missing some part of the question?
使用 new 修饰符显式隐藏从基类继承的成员。 要隐藏继承的成员,请在派生类中使用相同的名称声明它,并使用 new 修饰符对其进行修改。 这将产生您想要的行为。
有关更多信息,请访问此处:链接
Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier. This will result in exactly the behavior you want.
For more info go here: Link