日期:2014-05-17  浏览次数:20807 次

基类实现了接口,子类还需要再实现吗?子类如何再实现该接口的方法?
基类实现了接口,子类还需要实现吗?子类再实现会覆盖基类的接口方法吗?例如:
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()?
------最佳解决方案--------------------
这是因为其实子类中的 Method 方法是一个新的方法,并不是实现的接口中定义的方法,如果你在父类的method方法前加上virtual关键字然后在子类中用 override 重写父类的方法就是你需要的效果了,最后一行就会调用子类中的方法了
------其他解决方案--------------------
public interface IPrint
    {
        void Print();
    }

 public class ParentClass:IPrint
    {
        public virtual void Print()
        {
            Console.WriteLine("父类(ParentClass)打印");
        }
    }

 public class ChildClass:ParentClass
    {
        public override void Print()
    &