zoukankan      html  css  js  c++  java
  • c#学习历程3

    多态

    class Animal
        {
            private int age;
            public int Age
            {
                set{ age = value;}
                get{ return age;}
            }
            public virtual void Voice()
            {
                Console.WriteLine ("Animal");
            }
        }
    class House:Animal
        {
            public override void Voice()
            {
                Console.WriteLine ("House");
            }
        }
    class Sheep:Animal
        {
            public override void Voice()
            {
                Console.WriteLine ("Shpeep");
            }
        }


    //多态(一个方法多种状态)
                Animal a = new House ();
                Animal b = new Sheep ();
                Method (a);
                Method (b);
                //如果没虚函数,则10个动物需要写10个方法,每次不同对象调用method,
                //就需要写该对象的方法,如果有虚函数,则形参只需要为父对象,
                //通过父类指向类实现调用不同子类的方法,替代了原来的10种子类的方法,从而实现多态

    只有虚方法才能被重写

    abstract class Class
        {
            //抽象类相当于c++纯虚函数
            public abstract void print();
        }
        class ClassA:Class
        {
            //可以重写抽象类(abstract)和虚函数(virture)override
            public override void print()
            {
                Console.WriteLine ("Class A");
            }
        }
        class ClassB:ClassA
        {
            public override void print()
            {
                Console.WriteLine ("Class B");
            }
        }

     子类继承与父类的虚方法,虽然该子类重写虚方法,但它还是虚方法,下代们的子类可以重写虚方法  

    隐藏
    子类可以隐藏父类的方法,不过在c#中会发出警告,添加一个new就ok了
    使用new修饰,可以隐藏同名函数。

    class ClassA//没有指定继承,则默认继承object
        {
            public int x;
            public int y;
            public ClassA(int _x,int _y)
            {
                x = _x;
                y = _y;
            }
            public void Method()
            {
                Console.WriteLine ("classA Method");
            }
        }
        class ClassB:ClassA
        {
            public int z;
            public ClassB(int _x,int _y,int _z):base(_x,_y)//只能用base(父类)
            {
                z=_z;
            }
            public new void Method()
            {
                Console.WriteLine ("classB Method");
            }
        }


              
  • 相关阅读:
    JB的IDE可视化MongoDB、MySQL数据库信息
    爬取QQ音乐(讲解爬虫思路)
    selenium实现淘宝的商品爬取
    爬取中国福彩网并做可视化分析
    Django的学习进阶(二)———— name
    xpath获取一个标签下的多个同级标签
    selenium中动作链的使用
    Error: Cannot find module 'electron-prebuilt'
    error Invalid tag name "–save-dev": Tags may not have any characters that encodeURIComponent encodes
    TypeError:mainWindow.loadUrl is not a function
  • 原文地址:https://www.cnblogs.com/shuaigezhaoguang/p/5869754.html
Copyright © 2011-2022 走看看