【问题标题】:Why is dynamic binding not working the way I expect it to in the following code?为什么动态绑定不能按照我在以下代码中的预期方式工作?
【发布时间】:2019-12-31 16:46:58
【问题描述】:

我已阅读以下关于动态绑定的声明:

调用哪个方法取决于变量的实际类型而不是声明的类型。这称为动态绑定。

但是为什么下面的代码没有按照我的预期工作呢?

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 这不应该是 Child.SomeMethod 吗?我很困惑,请解释一下

【问题讨论】:

    标签: c#


    【解决方案1】:

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

    Parent parent1 = new Child();
    

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

    因此,由于变量类型 (Parent parent1),编译器将在编译时解析 Parent 的 AnotherMethod 符号,而不管在堆上分配的实际运行时类型是 Child 实例.

    您可以使用另一个 downcast 访问 Child AnotherMethod

    ((Child)parent1).AnotherMethod();
    

    【讨论】:

      【解决方案2】:

      来自New Vs Override

      您不能覆盖非虚拟或静态方法。被覆盖的基方法必须是虚拟的、抽象的或覆盖的。

      来自new modifier (C# Reference)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多