在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
建议94:区别对待override和new override和new使类型体系应为继承而呈现出多态性。多态要求子类具有与基类同名的方法,override和new的作用就是:
我们来看一个继承体系: public class Shape { public virtual void MethodVirtual() { Console.WriteLine("base MethodVirtual call"); } public void Method() { Console.WriteLine("base Method call"); } } class Circle : Shape { public override void MethodVirtual() { Console.WriteLine("circle override MethodVirtual"); } } class Rectangle : Shape { } class Triangle : Shape { public new void MethodVirtual() { Console.WriteLine("triangle new MethodVirtual"); } public new void Method() { Console.WriteLine("triangle new Method"); } } class Diamond : Shape { public void MethodVirtual() { Console.WriteLine("Diamond default MethodVirtual"); } public void Method() { Console.WriteLine("Diamond default Method"); } } Shape是所有子类的基类。 Circle类override父类的MethodVirtual,所以即使子类转型为Shape,调用的还是子类方法: Shape s = new Circle(); s.MethodVirtual(); s.Method(); 输出为: circle override MethodVirtual Circle s = new Circle(); s.MethodVirtual(); s.Method(); 输出也为: circle override MethodVirtual 类型Rectangle没有对基类做任何处理,所以无论是否转型为Shape,调用的都是基类Shape的方法。 Shape s = new Triangle(); s.MethodVirtual(); s.Method(); 因为子类应经new了父类的方法,故子类方法和基类方法完全没有关系了,只要s被转型为Shape,针对s调用搞得都是父类方法。 Triangle triangle = new Triangle(); triangle.MethodVirtual(); triangle.Method(); 调用的都是子类方法,输出为: triangle new MethodVirtual
Shape s=new Diamond(); s.MethodVirtual(); s.Method(); 编译器会默认new的效果,所以输出和显示设置为new时一样。 输出为: base MethodVirtual call Diamond s = new Diamond(); s.MethodVirtual(); s.Method(); 输出为: Diamond default MethodVirtual static void Main(string[] args) { TestShape(); TestDerive(); TestDerive2(); } private static void TestShape() { Console.WriteLine("TestShape\tStart"); List<Shape> shapes = new List<Shape>(); shapes.Add(new Circle()); shapes.Add(new Rectangle()); shapes.Add(new Triangle()); shapes.Add(new Diamond()); foreach (Shape s in shapes) { s.MethodVirtual(); s.Method(); } Console.WriteLine("TestShape\tEnd\n"); } private static void TestDerive() { Console.WriteLine("TestDerive\tStart"); Circle circle = new Circle(); Rectangle rectangle = new Rectangle(); Triangle triangel = new Triangle(); Diamond diamond = new Diamond(); circle.MethodVirtual(); circle.Method(); rectangle.MethodVirtual(); rectangle.Method(); triangel.MethodVirtual(); triangel.Method(); diamond.MethodVirtual(); diamond.Method(); Console.WriteLine("TestShape\tEnd\n"); } private static void TestDerive2() { Console.WriteLine("TestDerive2\tStart"); Circle circle = new Circle(); PrintShape(circle); Rectangle rectangle = new Rectangle(); PrintShape(rectangle); Triangle triangel = new Triangle(); PrintShape(triangel); Diamond diamond = new Diamond(); PrintShape(diamond); Console.WriteLine("TestDerive2\tEnd\n"); } static void PrintShape(Shape sharpe) { sharpe.MethodVirtual(); sharpe.Method(); } 输出为: TestShape Start
转自:《编写高质量代码改善C#程序的157个建议》陆敏技 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论