我已阅读以下有关动态绑定(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
符号在 Child
和 Parent
之间重用(即没有动态绑定(bind)在 AnotherMethod
上)。
因此,由于变量类型 (Parent Parent1
),编译器将在编译时解析 Parent 的 AnotherMethod
符号,无论实际运行时如何堆上分配的类型是 Child
实例。
您可以使用另一个向下转换来访问子AnotherMethod
:
((Child)parent1).AnotherMethod();
关于c# - 为什么动态绑定(bind)在以下代码中没有按照我期望的方式工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59541044/