google0312 发表于 2016-10-12 08:52:03

C#入门基础——使用new之后继承的区别

使用虚方法(virtual)和覆写(override)方法可以使基类的引用访问“升级”到派生类中。
而在最高继承使用了new之后,基类的引用不会再最高继承中出现,只能到最后一个覆写(override)方法中体现。

namespace 使用声明的虚方法和覆盖的实例
{
    class Program
    {
      static void Main(string[] args)
      {
            SecondDerived derived = new SecondDerived();   //实例化
            MyBaseClass mybc = derived;                  //强制转换成基类
            derived.Print();
            mybc.Print();
            Console.ReadKey();
      }
    }
    class MyBaseClass
    {
         virtual public void Print()         //虚方法
      {
            Console.WriteLine("This is the base class.");
      }
    }
    class MyDerivedClass : MyBaseClass       //派生类
    {
         override public void Print()      //覆写方法
      {
            Console.WriteLine("This is the derived class.");
      }
    }
    class SecondDerived : MyDerivedClass    //派生类
    {
      override public void Print()
      {
            Console.WriteLine("This is the second derived class.");
      }
    }
}
输出结果
This is the second derived class.
This is the second derived class.

namespace 使用new声明的虚方法和覆盖的实例
{
    class Program
    {
      static void Main(string[] args)
      {
            SecondDerived derived = new SecondDerived();   //实例化
            MyBaseClass mybc = derived;                  //强制转换成基类
            derived.Print();
            mybc.Print();
            Console.ReadKey();
      }
    }
    class MyBaseClass
    {
         virtual public void Print()         //虚方法
      {
            Console.WriteLine("This is the base class.");
      }
    }
    class MyDerivedClass : MyBaseClass       //派生类
    {
         override public void Print()      //覆写方法
      {
            Console.WriteLine("This is the derived class.");
      }
    }
    class SecondDerived : MyDerivedClass    //派生类
    {
      new public void Print()      //隐藏继承成员
      {
            Console.WriteLine("This is the second derived class.");
      }
    }
}

输出结果
This is the second derived class.
This is the derived class.

match123_xbd 发表于 2023-4-3 12:58:56

{:7_141:}
页: [1]
查看完整版本: C#入门基础——使用new之后继承的区别