【发布时间】: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#