[C#] C# 中使用 override 和 new 关键字进行版本控制 →→→→→进入此内容的聊天室

来自 , 2021-03-12, 写在 C#, 查看 150 次.
URL http://www.code666.cn/view/da94cbef
  1. // versioning.cs
  2. // 需要 CS0114
  3. public class MyBase
  4. {
  5.    public virtual string Meth1()
  6.    {
  7.       return "MyBase-Meth1";
  8.    }
  9.    public virtual string Meth2()
  10.    {
  11.       return "MyBase-Meth2";
  12.    }
  13.    public virtual string Meth3()
  14.    {
  15.       return "MyBase-Meth3";
  16.    }
  17. }
  18.  
  19. class MyDerived : MyBase
  20. {
  21.    // 使用 override 关键字重写虚方法 Meth1:
  22.    public override string Meth1()
  23.    {
  24.       return "MyDerived-Meth1";
  25.    }
  26.    // 使用 new 关键字显式隐藏
  27.    // 虚方法 Meth2:
  28.    public new string Meth2()
  29.    {
  30.       return "MyDerived-Meth2";
  31.    }
  32.    // 由于下面声明中没有指定任何关键字,
  33.    // 因此将发出一个警告来提醒程序员
  34.    // 该方法隐藏了继承的成员 MyBase.Meth3():
  35.    public string Meth3()
  36.    {
  37.       return "MyDerived-Meth3";
  38.    }
  39.  
  40.    public static void Main()
  41.    {
  42.       MyDerived mD = new MyDerived();
  43.       MyBase mB = (MyBase) mD;
  44.  
  45.       System.Console.WriteLine(mB.Meth1());
  46.       System.Console.WriteLine(mB.Meth2());
  47.       System.Console.WriteLine(mB.Meth3());
  48.    }
  49. }
  50.  
  51. //csharp/4930

回复 "C# 中使用 override 和 new 关键字进行版本控制"

这儿你可以回复上面这条便签

captcha