C# 为什么动态绑定没有按照我在下面代码中期望的方式工作?
我已经阅读了以下关于动态绑定的声明: 调用哪个方法由变量的实际类型和未声明的类型决定。这就是所谓的动态绑定 但是为什么下面的代码没有按我期望的方式工作呢C# 为什么动态绑定没有按照我在下面代码中期望的方式工作?,c#,C#,我已经阅读了以下关于动态绑定的声明: 调用哪个方法由变量的实际类型和未声明的类型决定。这就是所谓的动态绑定 但是为什么下面的代码没有按我期望的方式工作呢 class Program { static void Main(string[] args) { Parent parent = new Parent(); parent.SomeMethod(); // overriden parent.AnotherMethod(); //
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.AnotherMethodFrom 不能重写非虚拟或静态方法。被重写的基方法必须是虚拟的、抽象的或重写的
从中,您正在将变量parent1向上转换回本作业中的类类型Parent:
Parent parent1 = new Child();
因为AnotherMethod
不是多态的(因为您没有应用virtual
/override
),事实上,您已经明确添加了new
关键字,告诉编译器AnotherMethod
符号在Child
和Parent
之间重用(即,AnotherMethod
上没有动态绑定)
因此,由于变量类型(Parent parent1
),编译器将在编译时解析父对象的AnotherMethod
符号,而不管堆上分配的实际运行时类型是子实例
您可以使用另一个向下广播访问子AnotherMethod
:
((Child)parent1).AnotherMethod();