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关键字

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

  • 相关阅读:
    很好的Socket教程
    TcpClient 错误"不能做任何连接,因为目标机器积极地拒绝它" 的解决
    Tcp通信 暑期学习笔记(二)
    svn1.5+TortoiseSVN1.5+VisualSVN1.5
    进程、线程、应用程序域 暑期学习笔记(一)
    线程状态(转)
    Udp通信 暑期学习笔记(三)
    杜婧/于洋(为奥运冠军名字作诗)
    王峰(为奥运冠军名字作诗)
    刘子歌(为奥运冠军名字作诗)
  • 原文地址:https://www.cnblogs.com/zhang1997/p/7682474.html
Copyright © 2011-2022 走看看