C#类继承和接口继承时一些模棱两可的问题[转]

原文地址:http://www.cnblogs.com/harleyhu/archive/2012/11/29/2794809.html

 

1.在father定义的方法若含有virtual关键字,child继承后并且使用override重写这个方法,

那么当father f= new child();的时候,f操作的这个方法将是child的.
2.接上,若child继承后只是用new 该方法而不是override,那么father f = new child()时,

发操作的这个方法是father上的.

3.接口里定义的方法在被father(第一级)继承后,若在father中没有使用virtual关键字修

饰方法,那么该方法将不能被child继承,child继承father,必须用new来重新实现接口中的方

法. 若要用接口来引用child,child必须继承该接口

4.接上,father中实现了接口方法且用了virtual关键字,child可以使用override来重写它,

5.当father实现接口方法而没有用 virtual关键字,child也继承接口并且用new实现接口方法

,用Interface强制转化father和child的时候,      father f = new child();
            f.Dispose();//调用的是father.
            ((father)f).Dispose();//调用的是father.
            ((IDisposable)f).Dispose();//调用的是child.

6.当father实现接口且用virtual关键字,child并且overide接口方法,此时child可以不用继

承接口,当然继承也没事
             father f = new child();
            f.Dispose();//调用的是child
            ((father)f).Dispose();//调用的是child.
            ((IDisposable)f).Dispose();//调用的是child.

7.当father实现接口没用virtual,child用new实现接口方法,但是child没有继承接口
father f = new child();
            f.Dispose();//调用的是father
            ((father)f).Dispose();//调用的是father .
            ((IDisposable)f).Dispose();//调用的是father .,特殊注明,因为child被

IDisposable转化时,只能最多到father哪里,因为child不直接继承此接口

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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

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

    class InheritClass : BaseClass
    {
        public override 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();
        }
    }
}

 

posted @ 2017-01-06 16:44  翼龙zyl  阅读(1397)  评论(0编辑  收藏  举报