在C#中子类继承抽象类的时候,new 和override都可以用来修饰子类方法,但两者之间是有区别的。
相同点:
不同点:
怎么选择new还是override?
下面是代码示例:
- using System;
- namespace TestNamespace
- {
- // 基类
- public abstract class BaseClass
- {
- public string DoSomething()
- {
- return "BaseClass.DoSomething()";
- }
- public virtual string DoSomething2()
- {
- return "BaseClass.DoSomething()2";
- }
- }
-
- // 子类
- public partial class ChildClass : BaseClass
- {
- public new string DoSomething()
- {
- return "ChildClass. DoSomething()";
- //return base.DoSomething();
- }
-
- public override string DoSomething2()
- {
- return "ChildClass. DoSomething()2";
- //return base.DoSomething2();
- }
- }
- }
调用方法:
- /
- ChildClass child = new ChildClass();
- child.DoSomething(); // 调用子类同名方法DoSomething()
- child.DoSomething2() // 调用子类同名方法DoSomething2()
-
- /
- BaseClass child = new ChildClass();
- child.DoSomething(); // 调用基类同名方法DoSomething()
- child.DoSomething2() // 调用子类同名方法DoSomething2()
-
-
从上面的代码示例中可以发现,一旦基类的虚方法被override,我们就无法再访问基类的DoSomething()方法,除非是在子类方法中用base.DoSomething()去访问,但对于new修饰的子类同名方法,我们还是可以访问。