C# - 关键字使用 virtual+override 与 new
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/159978/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# - Keyword usage virtual+override vs. new
提问by i3ensays
What are differences between declaring a method in a base type "virtual
" and then overriding it in a child type using the "override
" keyword as opposed to simply using the "new
" keyword when declaring the matching method in the child type?
在基类型“ virtual
”中声明方法然后在子类型中使用“ override
”关键字覆盖它与在子类型中new
声明匹配方法时仅使用“ ”关键字相比有什么区别?
采纳答案by albertein
The "new" keyword doesn't override, it signifies a new method that has nothing to do with the base class method.
“new”关键字不会被覆盖,它表示一个与基类方法无关的新方法。
public class Foo
{
public bool DoSomething() { return false; }
}
public class Bar : Foo
{
public new bool DoSomething() { return true; }
}
public class Test
{
public static void Main ()
{
Foo test = new Bar ();
Console.WriteLine (test.DoSomething ());
}
}
This prints false, if you used override it would have printed true.
这将打印 false,如果您使用 override 它将打印 true。
(Base code taken from Joseph Daigle)
(基本代码取自 Joseph Daigle)
So, if you are doing real polymorphism you SHOULD ALWAYS OVERRIDE. The only place where you need to use "new" is when the method is not related in any way to the base class version.
所以,如果你正在做真正的多态性,你应该总是 OVERRIDE。唯一需要使用“new”的地方是该方法与基类版本没有任何关系。
回答by Joseph Daigle
The new
keyword actually creates a completely new member that only exists on that specific type.
该new
关键字实际上创建了一个仅存在于该特定类型的全新成员。
For instance
例如
public class Foo
{
public bool DoSomething() { return false; }
}
public class Bar : Foo
{
public new bool DoSomething() { return true; }
}
The method exists on both types. When you use reflection and get the members of type Bar
, you will actually find 2 methods called DoSomething()
that look exactly the same. By using new
you effectively hide the implementation in the base class, so that when classes derive from Bar
(in my example) the method call to base.DoSomething()
goes to Bar
and not Foo
.
该方法存在于两种类型上。当您使用反射并获取 type 的成员时Bar
,您实际上会发现调用的 2 个方法DoSomething()
看起来完全相同。通过使用,new
您可以有效地隐藏基类中的实现,以便当类派生自Bar
(在我的示例中)时,方法调用base.DoSomething()
转到Bar
而不是Foo
。
回答by Nescio
回答by Franci Penov
Here's some code to understand the difference in the behavior of virtual and non-virtual methods:
下面是一些代码来理解虚方法和非虚方法的行为差异:
class A
{
public void foo()
{
Console.WriteLine("A::foo()");
}
public virtual void bar()
{
Console.WriteLine("A::bar()");
}
}
class B : A
{
public new void foo()
{
Console.WriteLine("B::foo()");
}
public override void bar()
{
Console.WriteLine("B::bar()");
}
}
class Program
{
static int Main(string[] args)
{
B b = new B();
A a = b;
a.foo(); // Prints A::foo
b.foo(); // Prints B::foo
a.bar(); // Prints B::bar
b.bar(); // Prints B::bar
return 0;
}
}
回答by tvanfosson
Beyond just the technical details, I think using virtual/override communicates a lot of semantic information on the design. When you declare a method virtual, you indicate that you expect that implementing classes may want to provide their own, non-default implementations. Omitting this in a base class, likewise, declares the expectation that the default method ought to suffice for all implementing classes. Similarly, one can use abstract declarations to force implementing classes to provide their own implementation. Again, I think this communicates a lot about how the programmer expects the code to be used. If I were writing both the base and implementing classes and found myself using new I'd seriously rethink the decision not to make the method virtual in the parent and declare my intent specifically.
除了技术细节之外,我认为使用 virtual/override 在设计上传达了很多语义信息。当您声明一个虚拟方法时,您表明您希望实现类可能希望提供它们自己的非默认实现。同样,在基类中省略这一点,声明默认方法应该足以满足所有实现类的期望。类似地,可以使用抽象声明来强制实现类提供它们自己的实现。同样,我认为这在很大程度上传达了程序员希望如何使用代码。如果我同时编写基类和实现类并发现自己使用 new 我会认真重新考虑不使父类中的方法成为虚拟方法并明确声明我的意图的决定。
回答by Wedge
virtual / overridetells the compiler that the two methods are related and that in some circumstances when you would think you are calling the first (virtual) method it's actually correct to call the second (overridden) method instead. This is the foundation of polymorphism.
virtual / override告诉编译器这两个方法是相关的,并且在某些情况下,当您认为您正在调用第一个(虚拟)方法时,实际上调用第二个(覆盖)方法是正确的。这是多态的基础。
(new SubClass() as BaseClass).VirtualFoo()
Will call the SubClass's overriden VirtualFoo() method.
将调用子类的重写 VirtualFoo() 方法。
newtells the compiler that you are adding a method to a derived class with the same name as a method in the base class, but they have no relationship to each other.
new告诉编译器您正在向与基类中的方法同名的派生类添加一个方法,但它们彼此没有关系。
(new SubClass() as BaseClass).NewBar()
Will call the BaseClass's NewBar() method, whereas:
将调用 BaseClass 的 NewBar() 方法,而:
(new SubClass()).NewBar()
Will call the SubClass's NewBar() method.
将调用子类的 NewBar() 方法。
回答by Orion Edwards
I always find things like this more easily understood with pictures:
我总是发现这样的事情通过图片更容易理解:
Again, taking joseph daigle's code,
再一次,拿 joseph daigle 的代码,
public class Foo
{
public /*virtual*/ bool DoSomething() { return false; }
}
public class Bar : Foo
{
public /*override or new*/ bool DoSomething() { return true; }
}
If you then call the code like this:
如果你然后像这样调用代码:
Foo a = new Bar();
a.DoSomething();
NOTE: The important thing is that our object is actually a Bar
, but we are storing it in a variable of type Foo
(this is similar to casting it)
注意:重要的是我们的对象实际上是 a Bar
,但我们将它存储在一个类型的变量中Foo
(这类似于转换它)
Then the result will be as follows, depending on whether you used virtual
/override
or new
when declaring your classes.
那么结果将如下,这取决于你是使用virtual
/override
还是new
声明你的类时。
回答by Chetan
new
keyword is for Hiding. - means you are hiding your method at runtime. Output will be based base class method.override
for overriding. - means you are invoking your derived class method with the reference of base class. Output will be based on derived class method.
new
关键字用于隐藏。- 意味着您在运行时隐藏了您的方法。输出将基于基类方法。override
用于覆盖。- 表示您正在使用基类的引用调用派生类方法。输出将基于派生类方法。
回答by Dror Weiss
My version of explanation comes from using propertiesto help understand the differences.
我的解释版本来自使用属性来帮助理解差异。
override
is simple enough, right ? The underlying type overridesthe parent's.
override
够简单了吧?基础类型覆盖父类型。
new
is perhaps the misleading (for me it was). With properties it's easier to understand:
new
也许是误导(对我来说是)。使用属性更容易理解:
public class Foo
{
public bool GetSomething => false;
}
public class Bar : Foo
{
public new bool GetSomething => true;
}
public static void Main(string[] args)
{
Foo foo = new Bar();
Console.WriteLine(foo.GetSomething);
Bar bar = new Bar();
Console.WriteLine(bar.GetSomething);
}
Using a debugger you can notice that Foo foo
has 2GetSomething
properties, as it actually has 2 versions of the property, Foo
's and Bar
's, and to know which one to use, c# "picks" the property for the current type.
使用调试器,您会注意到它Foo foo
有2 个GetSomething
属性,因为它实际上有 2 个版本的属性,Foo
's 和Bar
's,并且要知道使用哪个版本,c#“选择”当前类型的属性。
If you wanted to use the Bar's version, you would have used override or use Foo foo
instead.
如果您想使用 Bar 的版本,您可以使用 override 或 useFoo foo
代替。
Bar bar
has only 1, as it wants completely newbehavior for GetSomething
.
Bar bar
只有1,因为它想要 的全新行为GetSomething
。
回答by Emre Tapc?
Not marking a method with anything means: Bind this method using the object's compile type, not runtime type (static binding).
不使用任何东西标记方法意味着:使用对象的编译类型绑定此方法,而不是运行时类型(静态绑定)。
Marking a method with virtual
means: Bind this method using the object's runtime type, not compile time type (dynamic binding).
使用方法标记方法virtual
:使用对象的运行时类型绑定此方法,而不是编译时类型(动态绑定)。
Marking a base class virtual
method with override
in derived class means: This is the method to be bound using the object's runtime type (dynamic binding).
在派生类中标记基类virtual
方法override
意味着:这是使用对象的运行时类型(动态绑定)绑定的方法。
Marking a base class virtual
method with new
in derived class means: This is a new method, that has no relation to the one with the same name in the base class and it should be bound using object's compile time type (static binding).
在派生类中标记基类virtual
方法new
意味着:这是一个新方法,与基类中的同名方法无关,应该使用对象的编译时类型(静态绑定)绑定。
Not marking a base class virtual
method in the derived class means: This method is marked as new
(static binding).
未virtual
在派生类中标记基类方法意味着:此方法被标记为new
(静态绑定)。
Marking a method abstract
means: This method is virtual, but I will not declare a body for it and its class is also abstract (dynamic binding).
标记一个方法abstract
意味着:这个方法是虚拟的,但我不会为它声明一个主体,它的类也是抽象的(动态绑定)。