何时应该将类成员声明为虚拟 (C#)/可覆盖 (VB.NET)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/81052/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 11:18:46  来源:igfitidea点击:

When should a class member be declared virtual (C#)/Overridable (VB.NET)?

提问by Alex Angas

Why wouldn't I choose abstract? What are the limitations to declaring a class member virtual? Can only methods be declared virtual?

为什么我不选择抽象?声明类成员虚拟有哪些限制?只能将方法声明为虚拟方法吗?

采纳答案by Kokuma

An abstract method or property (both can be virtual or abstract) can only be declared in an abstract class and cannot have a body, i.e. you can't implement it in your abstract class.

抽象方法或属性(都可以是虚拟的或抽象的)只能在抽象类中声明,不能有主体,即您不能在抽象类中实现它。

A virtual method or property must have a body, i.e. you must provide an implementation (even if the body is empty).

一个虚方法或属性必须有一个主体,即你必须提供一个实现(即使主体是空的)。

If someone want to use your abstract class, he will have to implement a class that inherits from it and explicitly implement the abstract methods and properties but can chose to not override the virtual methods and properties.

如果有人想使用您的抽象类,他将必须实现一个继承自它的类并显式实现抽象方法和属性,但可以选择不覆盖虚拟方法和属性。

Exemple :

例子:

using System;
using C=System.Console;

namespace Foo
{
    public class Bar
    {
        public static void Main(string[] args)
        {
            myImplementationOfTest miot = new myImplementationOfTest();
            miot.myVirtualMethod();
            miot.myOtherVirtualMethod();
            miot.myProperty = 42;
            miot.myAbstractMethod();
        }
    }

    public abstract class test
    {
        public abstract int myProperty
        {
            get;
            set;
        }

        public abstract void myAbstractMethod();

        public virtual void myVirtualMethod()
        {
            C.WriteLine("foo");
        }

        public virtual void myOtherVirtualMethod()
        {
        }
    }

    public class myImplementationOfTest : test
    {
        private int _foo;
        public override int myProperty
        {
            get { return _foo; }
            set { _foo = value; }
        }

        public override void myAbstractMethod()
        {
            C.WriteLine(myProperty);
        }

        public override void myOtherVirtualMethod()
        {
            C.WriteLine("bar");
        }
    }
}

回答by Maximilian

If you want to give it an implementation in your base class you make it virtual, if you don't you make it abstract.

如果你想在你的基类中给它一个实现,你就让它成为虚拟的,否则你就让它抽象。

Yes, only methods can be declared virtual.

是的,只有方法可以声明为虚拟的。

回答by Phil Wright

You would use abstract if you do not want to define any implementation in the base class and want to force it to be defined in any derived classes. Define it as a virtual if you want to provide a default implementatio that can be overriden by derived classes.

如果您不想在基类中定义任何实现并想强制它在任何派生类中定义,则可以使用抽象。如果您想提供可由派生类覆盖的默认实现,请将其定义为虚拟。

Yes, only methods can be virtual.

是的,只有方法可以是虚拟的。

回答by Seb Rose

Abstract means that you can't provide a default implementation. This in turn means that all subclasses must provide an implementation of the abstract method in order to be instantiable (concrete).

抽象意味着您不能提供默认实现。这反过来意味着所有子类必须提供抽象方法的实现才能实例化(具体)。

I'm not sure what you mean by 'limitations', so can't answer that point.

我不确定您所说的“限制”是什么意思,因此无法回答这一点。

Properties can be declared virtual, but you can conceptually think of them as methods too.

属性可以声明为虚拟的,但您也可以从概念上将它们视为方法。

回答by Richard Szalay

A member should be declared virtual if there is a base implementation, but there is a possibility of that functionality being overridden in a child class. Virtual can also be used instead of abstract to allow a method implementation to be optional (ie. the base implementation is an empty method)

如果存在基本实现,则成员应声明为 virtual,但该功能有可能在子类中被覆盖。Virtual 也可以用来代替 abstract 来允许方法实现是可选的(即基本实现是一个空方法)

There is no limitation when setting a member as virtual, but virtual members are slower than non-virtual methods.

将成员设置为虚拟时没有限制,但虚拟成员比非虚拟方法慢。

Both methods and properties can be marked as virtual.

方法和属性都可以标记为虚拟。

回答by Sakin

First of all, I will answer you second question. Only methods can be declared virtual. You would choose virtual instead of abstract when you want some default functionality in your base class, but you want to leave the option of overriding this functionality by classes that inherit from your base class. For examples:

首先,我将回答您的第二个问题。只有方法可以声明为虚拟的。当您想要基类中的某些默认功能时,您将选择虚拟而不是抽象,但您希望保留由从基类继承的类覆盖此功能的选项。举些例子:

If you are implementing the Shapeclass, you would probably have a method called getArea()that returns the area of your shape. In this case, there's no default behavior for the getArea() method in the Shape class, so you would implement it as abstract. Implementing a method as abstract will prevent you to instantiate a Shapeobject.

如果您正在实现Shape类,您可能会有一个名为getArea()的方法,该方法返回您的形状的面积。在这种情况下,Shape 类中的 getArea() 方法没有默认行为,因此您可以将其实现为abstract。将方法实现为抽象将阻止您实例化Shape对象。

On the other hand, if you implement the class Dog, you may want to implement the method Bark()in this case, you may want to implement a default barking sound and put it in the Dogclass, while some inherited classes, like the class Chiwawamay want to override this method and implement a specific barking sound. In this case, the method bark will be implemented as virtualand you will be able to instantiate Dogs as well as Chiwawas.

另一方面,如果你实现类Dog,你可能想在这种情况下实现Bark()方法,你可能想实现一个默认的吠叫声并将它放在Dog类中,而一些继承类,如类Chiwawa可能想要覆盖此方法并实现特定的吠叫声。在这种情况下,方法 bark 将作为虚拟实现,您将能够实例化 Dogs 和 Chiwawas。

回答by Benjol

There is a gotcha here to be aware of with Windows Forms.

这里有一个问题需要注意 Windows 窗体。

If you want a Control/UserControl from which you can inherit, even if you have no logic in the base class, you don't want it abstract, because otherwise you won't be able to use the Designer in the derived classes: http://www.urbanpotato.net/default.aspx/document/2001

如果你想要一个可以继承的 Control/UserControl,即使你在基类中没有逻辑,你也不希望它是抽象的,否则你将无法在派生类中使用设计器: http ://www.urbanpotato.net/default.aspx/document/2001

回答by Hallgrim

You question is more related to style than technicalities. I think that this book http://www.amazon.com/Framework-Design-Guidelines-Conventions-Development/dp/0321246756has great discussion around your question and lots of others.

您的问题与风格有关,而不是技术问题。我认为这本书 http://www.amazon.com/Framework-Design-Guidelines-Conventions-Development/dp/0321246756对您的问题和许多其他问题进行了很好的讨论。

回答by Chris Canal

I personally mark most methods and properties virtual. I use proxies and lazy loading alot, so I don't want to have to worry about changing things at a later date.

我个人将大多数方法和属性标记为虚拟。我经常使用代理和延迟加载,所以我不想担心以后更改内容。