zoukankan      html  css  js  c++  java
  • c#基础知识第十二节

    继承和多态

    继承(继承具有传递性)

    //(父类)
    class Animal
    {
    public string Name
    {
    get;
    set;
    }
    public void shout()
    {
    Console.WriteLine("动物叫");
    }
    }
    //(子类)
    class Dog : Animal
    {
    public void printName()
    {
    Console.WriteLine("名字 :"+Name);
    }
    }
    class Program
    {
    static void Main(string[] args)
    {
    //实例化子类
    Dog d = new Dog();
    d.Name = "沙皮狗";
    d.printName();
    d.shout();
    Console.ReadKey();
    }
    }

    如果拥有父类的话,在调用自身构造方法之前会先调用父类的构造方法。

    隐藏基类(父类)方法

    class Animal //父类
    {
    //父类方法
    public void Shout()
    {
    Console.WriteLine("动物叫!");
    }
    }
    //子类
    class Dog:Animal
    {
    //子类方法
    public new void Shout() //使用new关键字来隐藏基类方法
    {
    Console.WriteLine("狗叫!");
    }
    }
    class Program
    {
    static void Main(string[] args)
    {
    Dog d = new Dog();
    d.Shout();
    Console.ReadKey();
    }
    }

    密封(sealed)不能被继承

    object类

    class program

    {
    static void Main(string[] args)
    {
    Console.WriteLine(42.ToString());
    int i = 42;
    Console.WriteLine(i.ToString());

    Console.ReadKey();

    }
    }

    多态:同一方法在不同类中(希望父类方法在子类中得到一定的改进)

    class Animal //父类
    {
    //父类方法
    public virtual  void Shout()//使用virtual关键字来修饰要重写的父类方法
    {
    Console.WriteLine("动物叫!");
    }
    }
    //子类
    class Dog:Animal
    {
    //子类方法
    public override  void Shout() //使用override关键字来修饰,重写父类方法
    {
    Console.WriteLine("狗叫!");
    }
    }

    里氏转换原则

    1.Animal an=new Dog();

    2.Aniaml an=new Dog();

      Dog dog=(Dog)an;//将父类变量an强制转换为子类类型dog

    base关键字

    专门用于在子类中访问父类的成员

  • 相关阅读:
    让你一分钟认识电子身份验证系统EID
    jQuery滑动导航菜单
    sql语句中left join、 inner join的使用
    MySQL数据库分表的3种方法
    Apache 配置多端口 多虚拟主机 局域网访问
    8个开发必备的PHP功能(转)
    CentOS 6.4 图文安装教…
    mysql中char与varchar的区别分析
    PHP+jQuery+Ajax实现用户登录与退…
    隐藏/显示 我的电脑盘符驱动…
  • 原文地址:https://www.cnblogs.com/zhang1997/p/7682474.html
Copyright © 2011-2022 走看看