我们可以在c#的方法中同时使用virtual和new关键字吗?

nav*_*mar 4 c# function

我们可以在c#的方法中同时使用virtual和new关键字吗?

Jus*_*ner 7

是.您将定义一个隐藏父项方法并允许子项覆盖的方法.但这种行为可能有点奇怪.假设你有以下课程:

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!"); }
}
Run Code Online (Sandbox Code Playgroud)

然后你的执行看起来像:

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!
Run Code Online (Sandbox Code Playgroud)