I have two classes, one of them is Base and the other is Child, and both of them have the method Print with the same name and signature. These are my classes:
我有两个类,一个是Base,另一个是Child,它们都有相同名称和签名的Print方法。以下是我的课程:
class Base
{
public void Print() { Console.WriteLine("Base"); }
}
class Child : Base
{
public void Print() { Console.WriteLine("Child"); }
}
now, I'm trying to create an instance of Child and assign it to Base like this:
现在,我尝试创建一个Child实例,并将其分配给Base,如下所示:
Base obj = new Child();
obj.Print();
my question is, why does it show me "Base" in output? I expect to see "Child" in output because my instance is of type Child.
我的问题是,为什么它在输出中显示“Base”?我希望在输出中看到“Child”,因为我的实例是Child类型。
更多回答
You need to use virtual
and override
. See this answer for examples.
您需要使用虚拟和重写。有关示例,请参阅此答案。
This is a common mistake, however if you look closely at the compiler output you should be getting a CS0108 warning about not using the new keyword when declaring Child's Print method. learn.microsoft.com/en-us/dotnet/csharp/language-reference/…
这是一个常见的错误,然而,如果您仔细查看编译器输出,您应该会收到一个CS0108警告,警告您在声明Child的print方法时不要使用new关键字。Learn.microsoft.com/en-us/dotnet/csharp/language-reference/…
优秀答案推荐
You must mark the Print method of the Base instance as virtual so that its derived classes can override that method.
In your example:
必须将基本实例的Print方法标记为虚,以便其派生类可以重写该方法。在您的示例中:
class Base
{
public virtual void Print() { Console.WriteLine("Base"); }
}
class Child : Base
{
public override void Print() { Console.WriteLine("Child"); }
}
If you try now this code
如果您现在尝试此代码
Base obj = new Child()
obj.Print()
You should see in the Console
您应该在控制台中看到
Child
更多回答
我是一名优秀的程序员,十分优秀!