对基类强制覆盖方法

本文关键字:覆盖 方法 基类 | 更新日期: 2023-09-27 18:07:17

我有以下代码:

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中显示被覆盖的方法,这是可能的。

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

对基类强制覆盖方法

当我实例化根对象并调用我想要的Display()方法时在Child中显示被重写的方法是否可行。

需要创建Child类的实例。

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

当前你的对象temp持有基类的引用,它不知道任何关于子,因此从基类的输出。

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

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

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

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

不,这是不可能的你必须实例化一个子对象而不是根对象

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

如果你不想修改temp,那么你必须修改根显示方法,使其显示"child"而不是根

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

你需要创建一个Child类:

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

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

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

你应该得到你想要的输出