我们可以在c#的方法中同时使用virtual和new关键字吗?
最佳答案
是的。您将定义一个方法来隐藏父方法并允许子方法覆盖。虽然这种行为可能有点奇怪。假设您有以下类(class):
public class A
{
public void DoSomething(){ Console.WriteLine("42!"); }
}
public class B : A
{
public virtual new void DoSomething(){ Console.WriteLine("Not 42!"); }
}
public class C : B
{
public override void DoSomething(){ Console.WriteLine("43!"); }
}
然后你的执行看起来像这样:
A a = new A();
A bAsA = new B();
A cAsA = new C();
B b = new B();
B cAsB = new C();
C c = new C();
a.DoSomething(); // 42!
b.DoSomething(); // Not 42!
bAsA.DoSomething(); // 42!
c.DoSomething(); // 43!
cAsB.DoSomething(); // 43!
cAsA.DoSomething(); // 42!
关于c# - 我们可以在c#的方法中同时使用virtual和new关键字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3702744/