简体   繁体   English

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

[英]can we use both virtual and new keyword in methods of c#?

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

Yes. 是。 You would be defining a method that hid a method of a parent and allowed children to override. 您将定义一个隐藏父项方法并允许子项覆盖的方法。 The behavior might be a little strange though. 但这种行为可能有点奇怪。 Say you had the following classes: 假设你有以下课程:

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!"); }
}

Then your execution would look something like: 然后你的执行看起来像:

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!

Yes you can combine both. 是的你可以两者结合起来。

virtual allows a method to be overridden in a derived class virtual允许在派生类中重写方法

new allows you to hide the old method. new允许您隐藏旧方法。

Both are complementary and not contradicting. 两者都是互补的而不是矛盾的。

Don't hesitate to just try this yourself, Visual Studio makes it easy. 不要犹豫,自己尝试一下,Visual Studio让它变得简单。

class Base {
    public virtual void Method() { }
}
class Derived : Base {
    public virtual new void Method() { }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM