Is every abstract function virtual in C#, in general?
I was looking at Stack Overflow question What is the difference between abstract function and virtual function?, and I was wondering whether every abstract function should be considered to be a virtual function in C# or in general?
I was a bit puzzled by the "you must override/you may override" responses to that question. Not being a C# programmer, I tend to think that abstract functions are a compile-time concept only, and that abstract functions are virtual functions by definition since you must provide at least one but can provide multiple implementations further down the hierarchy.
Virtual functions have a compile-time dimension too, in that you cannot override a non-virtual function, but they are mostly a runtime concept since it is "just" the selection of the correct method implementation based on the actual receiver.
Yes. From section 10.6.6 of the C# 3.0 spec:
When an instance method declaration includes an abstract modifier, that method is said to be an abstract method. Although an abstract method is implicitly also a virtual method, it cannot have the modifier virtual.
It has to be virtual (and Jon Skeet has already whipped out the spec to prove that it is), because, given a reference to the abstract base class, the concrete derived class's implementation must be called. For example, given the classic Animal hierarchy:
abstract class Animal{
public abstract void Speak();
}
class Cat : Animal{
public override void Speak(){Console.WriteLine("meow");}
}
class Dog : Animal{
public override void Speak(){Console.WriteLine("bark");}
}
A function that takes an Animal
object, and calls its Speak
method wouldn't know which implementation to call if the function weren't virtual.
static void TalkToAnimal(Animal a){
Console.WriteLine("Hello, animal.");
a.Speak();
}
Note however, that interface implementations are not virtual by default. Because an interface works differently from a class, true polymorphism isn't necessary to find the implementation of an interface method.
Yes, it is. For proof:
abstract class A {
public abstract void Foo();
}
class B : A {
public override void Foo()
{ /* must do */ }
}
class C : B {
public override void Foo()
{ /* can do */ }
}
链接地址: http://www.djcxy.com/p/38120.html
上一篇: 用虚拟覆盖抽象方法