- 派生类中的方法前面带有
new
关键字,则该方法被定义为独立于基类中的方法。 - 派生类中的方法前面带有
override
关键字,则派生类的对象将调用该方法,而不是调用基类方法,以虚拟形式定义基类方法 - 派生类中使用
base
关键字调用基类方法using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OverrideAndNew2 { class Program { static void Main(string[] args) { TestCars1(); TestCars2(); TestCars3(); TestCars4(); } public static void TestCars1() { System.Console.WriteLine("\nTestCars1"); System.Console.WriteLine("----------"); Car car1 = new Car(); car1.DescribeCar(); System.Console.WriteLine("----------"); ConvertibleCar car2 = new ConvertibleCar(); car2.DescribeCar(); System.Console.WriteLine("----------"); Minivan car3 = new Minivan(); car3.DescribeCar(); System.Console.WriteLine("----------"); } // Output: // TestCars1 // ---------- // Four wheels and an engine. // Standard transportation. // ---------- // Four wheels and an engine. // Standard transportation. // ---------- // Four wheels and an engine. // Carries seven people. // ---------- public static void TestCars2() { System.Console.WriteLine("\nTestCars2"); System.Console.WriteLine("----------"); var cars = new List<Car> { new Car(), new ConvertibleCar(), new Minivan() }; foreach (var car in cars) { car.DescribeCar(); System.Console.WriteLine("----------"); } } // Output: // TestCars2 // ---------- // Four wheels and an engine. // Standard transportation. // ---------- // Four wheels and an engine. // Standard transportation. // ---------- // Four wheels and an engine. // Carries seven people. // ---------- public static void TestCars3() { System.Console.WriteLine("\nTestCars3"); System.Console.WriteLine("----------"); ConvertibleCar car2 = new ConvertibleCar(); Minivan car3 = new Minivan(); car2.ShowDetails(); car3.ShowDetails(); } // Output: // TestCars3 // ---------- // A roof that opens up. // Carries seven people. public static void TestCars4() { System.Console.WriteLine("\nTestCars4"); System.Console.WriteLine("----------"); Car car2 = new ConvertibleCar(); Car car3 = new Minivan(); car2.ShowDetails(); car3.ShowDetails(); } // Output: // TestCars4 // ---------- // Standard transportation. // Carries seven people. } class Car { public virtual void DescribeCar() { System.Console.WriteLine("Four wheels and an engine."); ShowDetails(); } public virtual void ShowDetails() { System.Console.WriteLine("Standard transportation."); } } class ConvertibleCar : Car { public new void ShowDetails() { System.Console.WriteLine("A roof that opens up."); } } class Minivan : Car { public override void ShowDetails() { System.Console.WriteLine("Carries seven people."); } } }
C# New override
于 2022-10-22 22:23:15 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)