c# 多态的理解

namespace console_父类子类
{
    class Program
    {
        public static void Main(string[] args)
        {
            showTest t = new showTest();
            // 情况1 默认情况下调用父类的方法
            t.show(new Son1()); //"i·m parent..."
            // 情况2 通过virtual 或 abstract 子类用 override 重写方法参与虚调用
            // c# 不能多继承,派生类重写某个虚拟成员时,即使该派生类的实例被当作基类的实例访问,也会调用该成员
            // 理解上面这句话很重要,当派生再次被继承时,他也是只调用实现了重写的虚方法,反之则调用最近实现重写的方法
            // 如果都没有实现则还是调用 基类的方法
            t.show(new Son1()); //"i·m son1..."
            t.show(new Son2()); //i·m son2...
            // 情况3 派生类通过new 来阻止 被调用
            t.show(new Son1()); //i·m parent...
            // 情况4 当派生中拥有相同的成员时    
            Console.WriteLine(((Parent)new Son1()).test1);
    
            // 情况5 当父类定义虚方法virtual 派生必须实现方法,new关键字可以阻止被调用
            // sealed 可以停止虚拟继承
            t.show(new Son2()); //"i·m son2..."
            // 报错 因为父类中相同的方法已经被sealed 修饰停止了虚拟继承
       // sealed 限制的是派生类被重写
t.show(new SonSon()); Console.ReadKey(true); } public static void test(IPerson p){ p.test(); } } //一个测试类 class showTest{ public void show(Parent p){ p.test(); } public void showproperty(Parent p){ Console.WriteLine(p.test1); } } //定义一个父类 class Parent{ //定义基类方法, 派生类重新次方法,默认情况下调用父类 public string test1 {get {return p;}} public string p = "p"; public virtual void test(){ Console.WriteLine("i·m parent..."); } } //子类 class Son1 : Parent { public string test1 {get {return p;}} public string p = "s"; public override void test(){ Console.WriteLine("i·m son1..."); } } //子类 class Son2 : Parent { public override void test(){ Console.WriteLine("i·m son2..."); } } class SonSon : Son2{ public override void test(){ Console.WriteLine("i`m sonson..."); } } interface IPerson{ void test(); } class Son3 : IPerson{ public void test(){ Console.WriteLine("i`m son3"); } } }

 

posted @ 2017-11-23 10:44  我是外婆  阅读(1542)  评论(0编辑  收藏  举报