zoukankan      html  css  js  c++  java
  • Virtual、Override和New关键字的使用

    当一个方法被声明为Virtual时,它是一个虚拟方法,直到你使用ClassName variable = new ClassName();声明一个类的实例之前,它都不存在于真实的内存空间中。这个关键字在类的继承中非常常用,用来提供类方法的多态性支持。


        virtual修饰的方法为虚方法,暗示其子类最好有自己的实现。
        override修饰的方法为重写方法,表示覆盖了基类原有方法的实现。

        new 关键字可以隐藏基类的方法,包括虚方法。

        通过下面的实例我们可以了解它们的具体使用,以及他们的区别。

    class Person
    {
    /// <summary>
    ///
    /// </summary>
    public Person() { Say(); }
    /// <summary>
    ///
    /// </summary>
    public virtual void Say()
    {
    Console.WriteLine(
    "Hello Person!");
    }
    }
    class Student:Person
    {
    /// <summary>
    ///
    /// </summary>
    public Student() { Say(); }
    /// <summary>
    ///
    /// </summary>
    public override void Say()
    {
    System.Console.WriteLine(
    "Hello Student!");
    }
    }

    class Teacher : Person
    {
    /// <summary>
    ///
    /// </summary>
    public Teacher() { Say(); }
    /// <summary>
    ///
    /// </summary>
    public new void Say()
    {
    Console.WriteLine(
    "Hello Teacher!");
    }
    }


    class Program
    {
    static void Main(string[] args)
    {

    Student s1
    = new Student();//Hello student,Hello student
    s1.Say(); //Hello student

    Console.WriteLine(
    "------------------------------------");

    Person s2
    = new Student(); //Hello student,Hello student
    s2.Say(); //Hello student

    Console.WriteLine(
    "------------------------------------");

    Teacher t1
    = new Teacher(); //Hello Person!Hello Teacher!
    t1.Say(); //Hello Teacher!

    Console.WriteLine(
    "------------------------------------");

    Person t2
    = new Teacher(); //Hello Person! Hello Teacher!
    t2.Say(); //Hello Person

    }
    }

    Override和New区别

    * 重写基类的方法,使用override关键字。 * 重写将替换基类的代码,即使通过基类访问也是这样。例如:

     *  Student s1 = new Student();//Hello student,Hello student
        s1.Say();                  //Hello student
     
     *隐藏基类的方法,用new关键字,尽管隐藏了基类的执行代码,但仍可以通过基类访问它,不管是虚拟方法还是非虚拟方法。例如:
     *  Person t2 = new Teacher(); //Hello Person! Hello Teacher!
        t2.Say();                  //Hello Person
     *

    扩展实例:

    public class A
    {
    public virtual void Fun1(int i)
    {
    Console.WriteLine(i);
    }

    public void Fun2(A a)
    {
    a.Fun1(
    1);
    Fun1(
    5);
    }
    }


    public class B : A
    {
    public override void Fun1(int i)
    {
    base.Fun1 (i + 1);
    }

    public static void Main()
    {
    B b
    = new B();
    A a
    = new A();
    a.Fun2(b);
    b.Fun2(a);
    }
    }
    结果是:

    2、5、1、6

  • 相关阅读:
    交叉熵--损失函数
    Window安装TensorFlow- GPU环境
    使用Tensorflow object detection API——训练模型(Window10系统)
    使用Tensorflow object detection API——环境搭建与测试
    由位图生成区域
    旋转位图
    获得当前颜色深度
    求多边形的面积
    MaskBlt 拷贝非矩形区域图象
    画多边型
  • 原文地址:https://www.cnblogs.com/yank/p/1023514.html
Copyright © 2011-2022 走看看