C# 什么是虚拟方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/622132/
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
What are Virtual Methods?
提问by
Why would you declare a method as "virtual".
为什么要将方法声明为“虚拟”。
What is the benefit in using virtual?
使用虚拟有什么好处?
回答by cgreeno
The VirtualModifier is used to mark that a method\property(ect) can be modified in a derived class by using the overridemodifier.
所述虚拟改性剂是用于标记的方法\属性(ECT)可以在派生类通过使用被修改覆盖改性剂。
Example:
例子:
class A
{
public virtual void Foo()
//DoStuff For A
}
class B : A
{
public override void Foo()
//DoStuff For B
//now call the base to do the stuff for A and B
//if required
base.Foo()
}
回答by PHeiberg
In order to be able to override it in inheriting classes.
为了能够在继承类中覆盖它。
Check out the MSDN entryfor the keyword. That explains it more in depth.
查看关键字的MSDN 条目。这更深入地解释了它。
回答by cyclo
Virtual methods are similar to abstract methods in base classes except their implementation on derived classes is optional. Also you could put logic in virtual method and override these in derived classes.
虚拟方法类似于基类中的抽象方法,只是它们在派生类上的实现是可选的。您也可以将逻辑放在虚拟方法中并在派生类中覆盖它们。
回答by Russ Cam
The virtual keyword is used to modify a method or property declaration, in which case the method or the property is called a virtual member. The implementation of a virtual member can be changed by an overriding member in a derived class.
When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member. (For more information on run-time type and most derived implementation, see 10.5.3 Virtual methods.)
By default, methods are non-virtual. You cannot override a non-virtual method.
You cannot use the virtual modifier with the following modifiers:
staticabstractoverride
Virtual properties behave like abstract methods, except for the differences in declaration and invocation syntax.
- It is an error to use the virtual modifier on a static property.
- A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
virtual 关键字用于修改方法或属性声明,在这种情况下,该方法或属性称为虚拟成员。派生类中的覆盖成员可以更改虚拟成员的实现。
当调用虚拟方法时,将检查对象的运行时类型是否有覆盖成员。调用最派生类中的覆盖成员,如果没有派生类覆盖该成员,则该成员可能是原始成员。(有关运行时类型和大多数派生实现的更多信息,请参阅 10.5.3 虚拟方法。)
默认情况下,方法是非虚拟的。您不能覆盖非虚拟方法。
您不能将虚拟修饰符与以下修饰符一起使用:
静态抽象覆盖
除了声明和调用语法的不同之外,虚拟属性的行为类似于抽象方法。
- 在静态属性上使用 virtual 修饰符是错误的。
- 通过包含使用 override 修饰符的属性声明,可以在派生类中覆盖虚拟继承的属性。
回答by tvanfosson
Even if you don't plan to derive from the class, marking the method virtual may be necessary in order to mock the class. Some mocking frameworks only allow you to mock virtual methods. Note that methods implementing an interface are virtual implicitly.
即使您不打算从该类派生,也可能需要将方法标记为 virtual 以模拟该类。一些模拟框架只允许你模拟虚拟方法。请注意,实现接口的方法是隐式虚拟的。
I use RhinoMocks which has this restriction and have taken to marking my methods virtual by default for just this reason. For me, this is probably the biggest reason to use virtual methods as the cases where inheritance comes into play are much less frequent.
我使用具有此限制的 RhinoMocks,并且出于这个原因默认将我的方法标记为虚拟。对我来说,这可能是使用虚方法的最大原因,因为继承发挥作用的情况要少得多。
回答by abhilash
Needless to say, virtual methods come in handy when your code is trying to abide with the Open Closed Principle
不用说,当您的代码试图遵守开放封闭原则时,虚拟方法会派上用场
Read More about the Open Closed Principle here, Uncle Bob's original OCP whitepaper.
在此处阅读有关开放封闭原则的更多信息,鲍勃叔叔的原始 OCP 白皮书。
Also pls be aware that methods are notvirtual by default in C# unlike Java.
另外请注意,与 Java 不同,C#中的方法默认情况下不是虚拟的。
回答by JaredPar
A virtual method is a type of method where the actual method calls depends on the runtime type of the underlying object.
虚拟方法是一种方法,其中实际方法调用取决于底层对象的运行时类型。
A non-virtual method is a type of method where the actual method called depends on the reference type of the object at the point of method invocation.
非虚方法是一种方法,其中调用的实际方法取决于方法调用点对象的引用类型。
回答by Ludington
Virtual allows an inheriting class to replace a method that the base class then uses.
Virtual 允许继承类替换基类随后使用的方法。
public class Thingy
{
public virtual void StepA()
{
Console.Out.WriteLine("Zing");
}
public void Action()
{
StepA();
Console.Out.WriteLine("A Thingy in Action.");
}
}
public class Widget : Thingy
{
public override void StepA()
{
Console.Out.WriteLine("Wiggy");
}
}
class Program
{
static void Main(string[] args)
{
Thingy thingy = new Thingy();
Widget widget = new Widget();
thingy.Action();
widget.Action();
Console.Out.WriteLine("Press any key to quit.");
Console.ReadKey();
}
}
When you run the Program your output will be:
当您运行程序时,您的输出将是:
Zing
A Thingy in Action.
Wiggy
A Thingy in Action.
Notice how even though Widget called the Action() method defined at the Thingy level, internally Thingy called Widget's StepA() method.
请注意,尽管 Widget 调用了在 Thingy 级别定义的 Action() 方法,但 Thingy 在内部调用了 Widget 的 StepA() 方法。
The basic answer is it gives inheritors of a class more flexibility. Of course, you've got to engineer your class well or it could weak havoc.
基本的答案是它为类的继承者提供了更大的灵活性。当然,你必须很好地设计你的课程,否则它可能会造成严重破坏。
回答by Stephane Halimi
A short question, a short answer! Qualify your method as "virtual" if you think you will inherit of the class it belongs to.
一个简短的问题,一个简短的答案!如果您认为您将继承它所属的类,则将您的方法限定为“虚拟”。
A longer answer: "virtual enables you to override, to give another meaning of your method in a derived class.
更长的答案:“虚拟使您能够覆盖,从而在派生类中赋予您的方法的另一种含义。
回答by Lineesh K Mohan
Virtual functions are the functions that doesn't really exists.The derived class can modify the virtual function by overriding it.Virtual functions are one of the way to achieve run time polymorphism
虚函数是实际上并不存在的函数。派生类可以通过覆盖它来修改虚函数。虚函数是实现运行时多态的方法之一
public class sample {
public virtual void fun(){
Console.WriteLine("base sample class \n");
}
}
public class A : sample{
public override void fun(){
Console.WriteLine("Class A \n");
}
}
public class B : sample{
public override void fun(){
Console.WriteLine("Class B \n");
}
}
class run{
public static void main(String[] args){
sample obj = new sample();
sample obj1 = new A();
sample obj2 = new B();
obj.fun();
obj1.fun();
obj2.fun();
}
}