gpt4 book ai didi

My method in child class does not get called(我的子类中的方法未被调用)

转载 作者:bug小助手 更新时间:2023-10-25 11:18:10 25 4
gpt4 key购买 nike



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/…

Eric Lippert wrote a bit about why C# allows non-virtual dispatch here: learn.microsoft.com/en-us/archive/blogs/ericlippert/…

Eric Lippert在这里写了一些关于为什么C#允许非虚拟分派的文章:learn.microsoft.com/en-us/archive/blogs/ericlippert/.

优秀答案推荐

You must mark the Print method of the Base instance as virtual so that its derived classes can override that method.
In your example:

必须将Base实例的Print方法标记为virtual,以便其派生类可以重写该方法。在您的示例中:


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

更多回答

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com