简体   繁体   English

方法可以是抽象的但不是虚拟的吗?

[英]Can a method be abstract but not virtual?

As I understand it, a method being marked abstract is implicitly virtual. 据我了解,标记为抽象的方法是隐式虚拟的。 The reason: Suppose the compile-time type of a given object is abstract. 原因:假设给定对象的编译时类型是抽象的。 If one of the object's abstract methods is being called, the actual method to be executed is the one defined in the object's runtime type. 如果正在调用对象的一个​​抽象方法,则要执行的实际方法是在对象的运行时类型中定义的方法。 Isn't it? 不是吗? If I'm right then the abstract method behaves as if it is also virtual. 如果我是对的,那么抽象方法的行为就好像它也是虚拟的。

In spite of that, I have successfully marked a C# method both abstract and virtual simultaneously: 尽管如此,我已经成功地同时标记了一个抽象和虚拟的C#方法:

public abstract virtual void crazy();

I suppose it means that an abstract method is not necessarily virtual and being abstract is actually orthogonal to being virtual. 我认为这意味着抽象方法不一定是虚拟的,而抽象方法实际上与虚拟方法正交。

What do I get wrong? 我有什么问题? How can an abstract method not be virtual? 抽象方法怎么不是虚拟的?

You cannot mark a method as both abstract and virtual . 您不能将方法标记为abstractvirtual It will result in a compiler error: 这将导致编译器错误:

The abstract method 'Namespace.Class.Foo()' cannot be marked virtual 抽象方法'Namespace.Class.Foo()'不能标记为虚拟

The rest of your question is correct: abstract methods are implicitly virtual . 你的问题的其余部分是正确的: abstract方法是隐式virtual

From MSDN 来自MSDN

  • An abstract method is implicitly a virtual method. 抽象方法隐含地是虚方法。
  • Abstract method declarations are only permitted in abstract classes. 抽象方法声明仅允许在抽象类中使用。
  • Because an abstract method declaration provides no actual implementation, there is no method body; 因为抽象方法声明没有提供实际的实现,所以没有方法体; the method declaration simply ends with a semicolon and there are no braces ({ }) following the signature. 方法声明只以分号结束,签名后面没有大括号({})。
  • The implementation is provided by an overriding method, which is a member of a non-abstract class. 该实现由重写方法提供,该方法是非抽象类的成员。
  • It is an error to use the static or virtual modifiers in an abstract method declaration. 在抽象方法声明中使用静态虚拟修饰符是错误的

"You cannot use the virtual modifier with the static, abstract, private, or override modifiers." “您不能将virtual修饰符与static,abstract,private或override修饰符一起使用。”

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

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