2

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:

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?

4

3 回答 3

8

您不能将方法同时标记为abstractvirtual。这将导致编译器错误:

抽象方法“Namespace.Class.Foo()”不能标记为虚拟

你的问题的其余部分是正确的:abstract方法是隐式的virtual

于 2013-02-20T13:10:04.937 回答
3

来自MSDN

  • 抽象方法隐含地是虚拟方法。
  • 抽象方法声明只允许在抽象类中。
  • 因为抽象方法声明没有提供实际的实现,所以没有方法体;方法声明仅以分号结尾,签名后没有大括号 ({ })。
  • 该实现由一个覆盖方法提供,该方法是非抽象类的成员。
  • 在抽象方法声明中使用staticvirtual修饰符是错误的。
于 2013-02-20T13:14:49.920 回答
2

“您不能将 virtual 修饰符与 static、abstract、private 或 override 修饰符一起使用。”

于 2013-02-20T13:10:34.280 回答