I have the following code:

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"

When I instantiate a Root object and call the Display() method I want to display the overridden method in Child is this possible.

I need this because I must create a plugin that's an extension to the base code and voids the Display() method of the Root class and implements only the plugin's method Child

有帮助吗?

解决方案 3

No it's not possible you have to instantiate a Child object instead of a root

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

if you don't want to modify temp then you have to modify Root display method to print "child" instead of root

其他提示

When I instantiate a Root object and call the Display() method I want to display the overridden method in Child is this possible.

You need to create instance of the Child class.

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

Currently your object temp is holding reference of the base class, it doesn't know anything about the child, hence the output from the base class.

When I instantiate a Root object and call the Display() method I want to display the overridden method in Child is this possible.

No. Suppose you add another class:

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

Then which method (Child.Display() or Child2.Display()) would you expect to be called for a Root instance?

It is not possible with your current code because you are creating a Root instance and not a Child instance. Therefore it has no idea about the Display method inside Child.

You'll need to create a Child class:

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

This is not how OOP works. You cannot use an overridden method in a base class. If you do this:

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

You should get your desired output.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top