zoukankan      html  css  js  c++  java
  • 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"); } } }
  • 相关阅读:
    C# winForm webBrowser页面中js调用winForm类方法(转)
    Shader开发工具: PVRShaman
    创建压缩纹理的工具
    Andriod NDK编译的时候无法使用math.h的函数。
    mongodb自动关闭:页面文件太小,无法完成操作
    通读cheerio API
    How to skip to next iteration in jQuery.each() util?
    在javascript中substr和substring的区别是什么
    运行代码时报linker command failed with exit code 1 错误
    软件开发模式对比(瀑布、迭代、螺旋、敏捷)
  • 原文地址:https://www.cnblogs.com/alplf123/p/7883674.html
Copyright © 2011-2022 走看看