简体   繁体   English

C# - 关键字使用 virtual+override 与 new

[英]C# - Keyword usage virtual+override vs. new

在基类型“ virtual ”中声明方法然后在子类型中使用“ override ”关键字覆盖它与在子类型中声明匹配方法时简单地使用“ new ”关键字相比有什么区别?

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)注意:重要的是我们的对象实际上是一个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

虚拟/覆盖说明图像

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 .所以,如果你正在做真正的多态性,你应该总是 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.唯一需要使用“new”的地方是该方法与基类版本没有任何关系。

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;
    }
}

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.当您使用反射并获取Bar类型的成员时,您实际上会发现两个名为DoSomething()方法看起来完全相同。 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 .通过使用new您可以有效地隐藏基类中的实现,因此当类从Bar派生时(在我的示例中),对base.DoSomething()的方法调用转到Bar而不是Foo

Beyond just the technical details, I think using virtual/override communicates a lot of semantic information on the design.除了技术细节之外,我认为使用 virtual/override 在设计上传达了很多语义信息。 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.如果我同时编写基类和实现类并发现自己使用 new 我会认真重新考虑不使父类中的方法成为虚拟方法并明确声明我的意图的决定。

virtual / override tells 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. virtual / override告诉编译器这两个方法是相关的,并且在某些情况下,当您认为您正在调用第一个(虚拟)方法时,实际上调用第二个(覆盖)方法是正确的。 This is the foundation of polymorphism.这是多态的基础。

(new SubClass() as BaseClass).VirtualFoo()

Will call the SubClass's overriden VirtualFoo() method.将调用子类的重写 VirtualFoo() 方法。

new tells 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() 方法。

The difference between the override keyword and new keyword is that the former does method overriding and the later does method hiding. override 关键字和 new 关键字的区别在于前者进行方法覆盖,后者进行方法隐藏。

Check out the folllowing links for more information...查看以下链接以获取更多信息...

MSDN and Other MSDN其他

  • new keyword is for Hiding. new关键字用于隐藏。 - means you are hiding your method at runtime. - 意味着您在运行时隐藏了您的方法。 Output will be based base class method.输出将基于基类方法。
  • override for overriding. override覆盖。 - means you are invoking your derived class method with the reference of base class. - 表示您正在使用基类的引用调用派生类方法。 Output will be based on derived class method.输出将基于派生类方法。

My version of explanation comes from using properties to help understand the differences.我的解释版本来自使用属性来帮助理解差异。

override is simple enough, right ? override很简单,对吧? The underlying type overrides the parent's.基础类型覆盖父类型。

new is perhaps the misleading (for me it was). new可能是误导(对我来说是)。 With properties it's easier to understand:使用属性更容易理解:

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 2 GetSomething 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 foo2 个GetSomething属性,因为它实际上有 2 个版本的属性, FooBar ,并且要知道使用哪个版本,c#“选择”当前类型的属性.

If you wanted to use the Bar's version, you would have used override or use Foo foo instead.如果您想使用 Bar 的版本,您可以使用 override 或使用Foo foo代替。

Bar bar has only 1 , as it wants completely new behavior for GetSomething . Bar bar只有1 ,因为它想要GetSomething全新行为。

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).在派生类中使用override标记基类virtual方法意味着:这是使用对象的运行时类型(动态绑定)绑定的方法。

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).在派生类中用new标记基类virtual方法意味着:这是一个新方法,与基类中的同名方法无关,应该使用对象的编译时类型(静态绑定)绑定。

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意味着:这个方法是虚拟的,但我不会为它声明一个主体,它的类也是抽象的(动态绑定)。

using System;  
using System.Text;  
  
namespace OverrideAndNew  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            BaseClass bc = new BaseClass();  
            DerivedClass dc = new DerivedClass();  
            BaseClass bcdc = new DerivedClass();  
  
            // The following two calls do what you would expect. They call  
            // the methods that are defined in BaseClass.  
            bc.Method1();  
            bc.Method2();  
            // Output:  
            // Base - Method1  
            // Base - Method2  
  
            // The following two calls do what you would expect. They call  
            // the methods that are defined in DerivedClass.  
            dc.Method1();  
            dc.Method2();  
            // Output:  
            // Derived - Method1  
            // Derived - Method2  
  
            // The following two calls produce different results, depending
            // on whether override (Method1) or new (Method2) is used.  
            bcdc.Method1();  
            bcdc.Method2();  
            // Output:  
            // Derived - Method1  
            // Base - Method2  
        }  
    }  
  
    class BaseClass  
    {  
        public virtual void Method1()  
        {  
            Console.WriteLine("Base - Method1");  
        }  
  
        public virtual void Method2()  
        {  
            Console.WriteLine("Base - Method2");  
        }  
    }  
  
    class DerivedClass : BaseClass  
    {  
        public override void Method1()  
        {  
            Console.WriteLine("Derived - Method1");  
        }  
  
        public new void Method2()  
        {  
            Console.WriteLine("Derived - Method2");  
        }  
    }  
}  

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

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