【问题标题】:What's going on with this method overloading?这个方法重载是怎么回事?
【发布时间】:2014-09-04 04:53:43
【问题描述】:

我有一个关于 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 设置为“那是父母”?我可能误解了 C# 中的方法重载。有没有办法强制代码使用 Child 调用(将 str1 设置为“That's a Child”)?

【问题讨论】:

标签: c# overloading


【解决方案1】:

为什么 str1 被设置为“That's a Parent”?

因为重载(通常)是在编译时确定的,而不是在执行时确定的。它完全基于目标和参数的编译时类型,使用dynamic 值的调用除外。

在你的例子中,参数类型是Parent,所以它调用MyClassName(Parent)

有没有办法强制代码使用 Child 调用(将 str1 设置为“That's a Child”)?

两种选择:

  • p 声明为Child 类型,而不是Parent
  • p 声明为dynamic 类型,这将强制在执行时执行重载决议

【讨论】:

  • 方案三:调用单个方法,然后检查类型。
  • 哇,我以前从未遇到过在 Excel com 互操作调用之外使用 dynamic 的情况。谢谢。
【解决方案2】:

方法重载解析发生在编译时,而虚方法覆盖解析发生在运行时

您对MyClassName() 的调用在编译时被解析为Parent 重载,因为p 的类型是Parent。因为Child 对象实际上也是Parent 的一个实例(由于继承),所以这不是问题。 (注意p instanceof Parent 为真,即使p 引用了Child 对象。)

【讨论】:

    猜你喜欢
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 2020-04-03
    • 2018-06-20
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多