1

我有以下代码:

public partial class Root : ICustomInterface
{
    public virtual void Display()
    {
        Console.WriteLine("Root");
        Console.ReadLine();
    }
}
public class Child : Root
{
    public override void Display()
    {
        Console.WriteLine("Child");
        Console.ReadLine();
    }
}
class Program
{
    static void Main(string[] args)
    {
        Root temp;
        temp = new Root();
        temp.Display();
    }
}

Output: "Root"
Desired output: "Child"

当我实例化一个Root对象并调用Display()我想要显示被覆盖的方法的方法时,Child这是否可能。

我需要这个,因为我必须创建一个插件,它是基本代码的扩展,并且Display()使类的方法无效Root并且只实现插件的方法Child

4

5 回答 5

6

当我实例化一个 Root 对象并调用 Display() 方法时,我想在 Child 中显示被覆盖的方法,这可能吗。

您需要创建Child类的实例。

Root temp;
temp = new Child(); //here
temp.Display();

目前您的对象temp持有基类的引用,它对子类一无所知,因此是基类的输出。

于 2013-04-04T09:10:02.543 回答
2

当我实例化一个 Root 对象并调用 Display() 方法时,我想在 Child 中显示被覆盖的方法,这可能吗。

不。假设您添加另一个类:

public class Child2 : Root
{
    public override void Display()
    {
        Console.WriteLine("Child 2");
        Console.ReadLine();
    }
}

那么您希望为实例调用哪个方法(Child.Display()或)?Child2.Display()Root

于 2013-04-04T09:12:32.503 回答
1

您当前的代码不可能,因为您正在创建一个Root实例而不是一个Child实例。因此它不知道Display里面的方法Child

您需要创建一个Child类:

Root temp;
temp = new Child();
temp.Display();
于 2013-04-04T09:11:11.197 回答
1

这不是 OOP 的工作方式。您不能在基类中使用被覆盖的方法。如果你这样做:

static void Main(string[] args)
{
    Root temp;
    temp = new Child();
    temp.Display();
}

你应该得到你想要的输出。

于 2013-04-04T09:11:53.333 回答
1

不,您不可能实例化一个子对象而不是根

Root temp;
temp = new Child();
temp.Display();

如果您不想修改 temp 那么您必须修改 Root 显示方法以打印“child”而不是 root

于 2013-04-04T09:11:55.643 回答