我对 C# 中的方法重载有疑问。我有一个父类和一个子类。
class Parent
{
public virtual string GetMyClassName()
{
return "I'm a Parent";
}
}
class Child : Parent
{
public override string GetMyClassName()
{
return "I'm a Child";
}
}
我在这两个类之外声明了两个静态方法,它们作用于任一类型的对象:
static string MyClassName(Parent parent)
{
return "That's a Parent";
}
static string MyClassName(Child child)
{
return "That's a Child";
}
当我测试如何调用这些方法时,我得到了一个我认为很奇怪的结果:
Parent p = new Child();
var str1 = MyClassName(p); // = "That's a Parent"
var str2 = p.GetMyClassName(); // = "I'm a Child"
为什么 str1
被设置为“That's a Parent”?我可能误解了 C# 中的方法重载。有没有办法强制代码使用 Child 调用(将 str1 设置为“That's a Child”)?
最佳答案
Why does str1 get set to "That's a Parent"?
因为重载(通常)是在编译时而不是执行时确定的。它完全基于目标和参数的编译时类型,使用 dynamic
值的调用除外。
在你的例子中,参数类型是Parent
,所以它调用MyClassName(Parent)
Is there a way to force the code use the Child call (setting str1 to "That's a Child")?
两种选择:
- 将
p
声明为Child
类型,而不是Parent
- 将
p
声明为dynamic
类型,这将强制在执行时执行重载决议
关于c# - 这个方法重载是怎么回事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25653396/