2013-04-04 51 views
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显示重写的方法这是可能的。

我需要这个,因为我必须创建一个插件,是一个扩展,基本代码和空洞的Root类的Display()方法,当我实例化一个根对象和呼叫仅实现插件的方法Child

+3

我不认为你完全理解继承。如果您希望Display()方法输出“Child”,您需要创建一个Child实例。 – 2013-04-04 09:11:03

+1

对于您编辑的部分问题,您应该看到:http://stackoverflow.com/questions/2779146/c-is-there-它是继承的方法 - 类 - 去除 - 方法,也是这样一个:http:// stackoverflow。com/questions/1125746/how-to-hide-remove-a-base-classs-methods-in-c – Habib 2013-04-04 09:25:54

回答

1

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

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

的,如果你不希望修改温度,那么你必须修改根目录显示方法打印“孩子”,而不是根

+0

我不想修改临时对象。 – XandrUu 2013-04-04 09:12:26

+0

然后修改根目录来代替显示“child”... – 2013-04-04 09:13:04

+0

我不想这样做,我想创建一个插件并且不修改项目的基本代码,插件必须是一个扩展,它会使Root方法和只调用我的Child方法。 – XandrUu 2013-04-04 09:16:46

6

Display()方法我想要 在Child中显示重写的方法是可能的。

您需要创建Child类的实例。

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

目前你的对象temp持有基类的引用,它不知道孩子什么,因此从基类的输出。

1

由于您正在创建Root实例而不是Child实例,因此无法使用当前代码。因此它不知道Child中的Display方法。

你需要创建一个Child类:

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

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

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

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

+0

我不想修改临时对象。 – XandrUu 2013-04-04 09:13:11

+2

然后你不知道你在做什么 – 2013-04-04 09:24:42

2

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

号假设你添加另一个类:

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

然后(Child.Display()Child2.Display())你会想到要呼吁Root例如哪种方法?