现在的位置: 首页 > 综合 > 正文

接口、虚方法和抽象方法的CLR处理

2013年01月04日 ⁄ 综合 ⁄ 共 859字 ⁄ 字号 评论关闭

下面通过一个例子,你可以看到CLR在处理接口、虚方法和抽象方法时的特点。

 public interface ICommon
    {
        void DoIt()
        {
        }
    }

    public class Base :ICommon
    {
        void ICommon.DoIt() { a(); }
        public virtual void DoIt() { b(); }
    }
    public class Derived :Base, ICommon
    {
        void ICommon.DoIt() { c(); }
        public new virtual void DoIt() { d(); }
    }
    public class ReallyDerived : Derived
    {
        public override void DoIt() { e(); }
    }

 

 static void Main(string[] args)
        {

            ReallyDerived r1 = new ReallyDerived();
            Derived r2 = r1;
            Base r3 = r1;
            ICommon r4 = r1;

            r1.DoIt();
            r2.DoIt();
            r3.DoIt();
            r4.DoIt();

        }

 

第一个方法将调用分发给e,因为对象的具体类型有一个名为DoIt的public方法;

第二个方法将调用分发给e,因为Derived.DoIt被声明为virtual;

第三个方法将调用分发给b,因为即便是Base.DoIt被声明为virtual,但后续的派生方法还是重载了它的使用;

第四个方法将调用分发给c,因为ICommon.DoIt隐式地为virtual。

当然,你可能不会这样写代码,不过,这可能(也可能不能)有助于你认识到CLR支持这种方式。

抱歉!评论已关闭.