c# - 这个方法重载是怎么回事?

标签 c# overloading

我对 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/

相关文章:

c# - 是否可以对 List<Interface> 施加类型约束?

c# - 验证不适用于 ImageButton 单击

c# - 如何查找 OpenReadAsync 方法抛出的异常

c++ - 自定义条件语句?这可能吗?

c++ - 是否可以合法地重载字符串文字和 const char*?

C++ 在模板类的情况下重载 operator+

c++ - SFINAE 在类型和非类型模板参数的情况下工作方式不同

c# - 如何将数据读取器转换为动态查询结果

c# - 打印 GTK Treeview Mono 中的所有行

function - 具有多个调用签名的 TypeScript 接口(interface)