c# - 为什么动态绑定(bind)在以下代码中没有按照我期望的方式工作?

标签 c#

我已阅读以下有关动态绑定(bind)的声明:

Which method to invoke is determined by variable's actual type and not declared type. This is known as dynamic binding.

但是为什么下面的代码没有按照我期望的方式工作?

class Program
{
    static void Main(string[] args)
    {
        Parent parent = new Parent();
        parent.SomeMethod(); // overriden 
        parent.AnotherMethod(); // hidden

        Child child = new Child();
        child.SomeMethod();
        child.AnotherMethod();

        System.Console.WriteLine("---------------------------------------");

        Parent parent1 = new Child();
        parent1.SomeMethod();
        parent1.AnotherMethod();


    }
}

class Parent
{
    public virtual void SomeMethod() //override
    {
        System.Console.WriteLine("Parent.SomeMethod");
    }

    public void AnotherMethod() //hide
    {
        System.Console.WriteLine("Parent.AnotherMethod");
    }
}

class Child : Parent
{
    public override void SomeMethod() //overriden
    {
        System.Console.WriteLine("Child.SomeMethod");
    }

    public new void AnotherMethod() //hidden
    {
        System.Console.WriteLine("Child.AnotherMethod");
    }

}

上述代码的输出为:

Parent.SomeMethod

Parent.AnotherMethod

Child.SomeMethod

Child.AnotherMethod


Child.SomeMethod

Parent.AnotherMethod <-- Shouldn't this be Child.SomeMethod? I'm confused please explain

最佳答案

您在此作业中将变量 parent1 向上转换回类类型 Parent:

Parent parent1 = new Child();

因为 AnotherMethod 不是多态的(因为您还没有应用 virtual/override),而且事实上您已经显式添加了new 关键字告诉编译器 AnotherMethod 符号在 ChildParent 之间重用(即没有动态绑定(bind)在 AnotherMethod 上)。

因此,由于变量类型 (Parent Parent1),编译器将在编译时解析 Parent 的 AnotherMethod 符号,无论实际运行时如何堆上分配的类型是 Child 实例。

您可以使用另一个向下转换来访问子AnotherMethod:

((Child)parent1).AnotherMethod();

关于c# - 为什么动态绑定(bind)在以下代码中没有按照我期望的方式工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59541044/

相关文章:

c# - 操作超时错误

c# - Unity 私有(private)唤醒更新和启动方法如何工作?

C# 反射代码不工作;

c# - 使用两个字段的组合作为字典中的键

c# - 我应该在 RavenDB 上使用 LINQ 查询吗?

c# - 策略模式 - "No Action"行为

c# - 不断的虐待?

c# - 将一些遗留的 VB.NET 代码转换为 C#,它在做什么?

c# - SetForegroundWindow 在 Windows Server 2008 上失败

c# - 正在删除文件,但访问被拒绝