zoukankan      html  css  js  c++  java
  • C#的override、new、vitutal一例

       1:  using System;
       2:  class A
       3:  {
       4:      public virtual void Method()
       5:      {
       6:          Console.WriteLine("A.method");
       7:      }
       8:  }
       9:   
      10:  class B:A
      11:  {
      12:      public new virtual void Method()
      13:      {
      14:          Console.WriteLine("B.method");
      15:      }
      16:  }
      17:   
      18:   
      19:  class C:B
      20:  {
      21:      public override void Method()
      22:      {
      23:          Console.WriteLine("C.Method");
      24:      }
      25:   
      26:   
      27:      public static void Main()
      28:      {
      29:          A a = new A();
      30:          B b = new C();
      31:          A c = b;
      32:   
      33:   
      34:          a.Method();
      35:   
      36:          //对于对象b,B是它的申明类,C类是它的实现类,先检查申明类
      37:          //发现Method()方法是vitual的,接着检查派生类C,发现Method方法被
      38:          //override修饰,所以就直接调用了C类的Method
      39:          b.Method();
      40:   
      41:          //对以对象c,它的申明类是A,实现类是B,它先检查自己的Method方法,
      42:          //发现A类的Method()方法是virtual方法,接着往下查找B类的Method方法
      43:          //发现B类的方法没有使用override,所以它自己调用它父类的方法,即A.method();
      44:   
      45:          c.Method();
      46:   
      47:      }
      48:  }
      49:   
      50:   
  • 相关阅读:
    LeetCode 55
    LeetCode 337
    LeetCode 287
    LeetCode 274
    LeetCode 278
    LeetCode 264
    LeetCode 189
    LeetCode 206
    LeetCode 142
    LeetCode 88
  • 原文地址:https://www.cnblogs.com/justinzhang/p/2177345.html
Copyright © 2011-2022 走看看