实现接口的类的继承 [英] Inheritance of classes that implements interfaces
本文介绍了实现接口的类的继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好.
我有这段代码来说明我的问题:
Hello everybody.
I have this piece of code to explain my problem:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
public interface Interface1
{
void Test();
}
public class BaseClass : Interface1
{
public void Test()
{
throw new NotImplementedException(); //Execution jumps here always. I need it to execute this line only if Class1 doesn't have a Test function.
}
}
public class Class1 : BaseClass
{
public void Test()
{
return; //Why not here?
}
}
class Program
{
static void Main(string[] args)
{
Class1 a = new Class1();
Object obj = a as Object;
Interface1 itf = a as Interface1;
itf.Test(); // <-- Why it calls BaseClass.Test() ?
}
}
}
当程序执行到Main函数中的itf.Test()时,我希望它会调用Class1.Test()函数而不是BaseClass.Test().仅当未实现Class1.Test()函数时,才需要执行BaseClass.Test()方法.在这种情况下,程序将触发NotImplementedException.
有人可以帮我吗?谢谢.
When the program execution reaches the itf.Test() in the Main function I expect it would call the Class1.Test() function instead of the BaseClass.Test(). I need to execute the BaseClass.Test() method only if Class1.Test() function is not implemented. In that case the program would fire a NotImplementedException.
Anyone could help me please? Thanks.
推荐答案
按如下所示更改代码:
Change your code as follows:
public class BaseClass : Interface1
{
public virtual void Test()
{
// some code here
}
}
public class Class1 : BaseClass
{
public override void Test()
{
// some other code here
}
}
上一个答案是正确的.您使用virtual表示可以重写该方法.在子类中重写该方法时,可以使用重写.
非虚拟方法:
*无法覆盖
*比虚拟方法(早期绑定)要快
虚方法:
*可以覆盖
*比非虚拟方法要慢,因为绑定是在运行时(后期绑定).
Previous answer is correct. You use virtual to indicate that the method can be overriden. And you use override when you are re-writing that method in a child class.
non virtual method:
* it can''t be overriden
* it''s faster than virtual method (early binding)
virtual method:
* it can be overriden
* it''s slower than non virtual method because the binding is at runtime (late binding).
这篇关于实现接口的类的继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文