基类实现了接口,子类还需要再实现吗?子类如何再实现该接口的方法?

CJW_King 2012-11-23 11:22:07
基类实现了接口,子类还需要实现吗?子类再实现会覆盖基类的接口方法吗?例如:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
interface IInterface
{
void Method();
}

class BaseClass : IInterface
{
public void Method()
{
Console.WriteLine("BaseClass Method()...");
}
}

class InheritClass : BaseClass
{
public void Method()
{
Console.WriteLine("Inherit Method()...");
}
}
class Program
{
static void Main(string[] args)
{
BaseClass bc = new BaseClass();
InheritClass ic = new InheritClass();
bc.Method();
ic.Method();
IInterface iif = new BaseClass();
iif.Method();
IInterface iif2 = new InheritClass();
iif2.Method();
Console.ReadKey();
}
}
}

运行结果:

为什么iif2.Method()调用的依然是BaseClass的Method()而不是InheritClass的Method()?
...全文
340 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
也许你注意到,编译时VS警告你这样会覆盖父类的方法,其实默认就是 class InheritClass : BaseClass { new public void Method() { Console.WriteLine("Inherit Method()..."); } } 这样InheritClass.Method()本身就不是BaseClass成员,也就不是IInterface成员。
hard_learner 2012-11-23
  • 打赏
  • 举报
回复
public interface IPrint { void Print(); } public class ParentClass:IPrint { public virtual void Print() { Console.WriteLine("父类(ParentClass)打印"); } } public class ChildClass:ParentClass { public override void Print() { Console.WriteLine("子类(ChildClass)打印"); } } ParentClass p = new ParentClass(); p.Print(); ChildClass c = new ChildClass(); c.Print(); IPrint i = new ParentClass(); i.Print(); i= new ChildClass(); i.Print(); Console.ReadKey();
hard_learner 2012-11-23
  • 打赏
  • 举报
回复
这是因为其实子类中的 Method 方法是一个新的方法,并不是实现的接口中定义的方法,如果你在父类的method方法前加上virtual关键字然后在子类中用 override 重写父类的方法就是你需要的效果了,最后一行就会调用子类中的方法了

110,565

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧