In Wagner's "Effective C#," item 23, he explains that
interface methods are not virtual...they are a declaration of a concrete implementation.
I find that to be a conundrum, because it means that interface methods represent early binding, and yet they have the behavior of late-binding. It rouses curiosity of how they work under the covers. In C++ this would turn into a discussion of vtables. In C#, I don't know what it turns into. Can som开发者_开发问答eone spell it out?
p.s. This question has a cousin, but this question focuses on interfaces.
p.p.s. Please don't worry about "you don't need to know how it works." Again, this is about curiosity.Right, they are not virtual from the language point of view. But they actually are as far as the CLR is concerned. This sample code:
class Example : IDisposable {
public void Dispose() {}
}
Produces this IL for the Dispose() method:
.method public hidebysig newslot virtual final // <=== here
instance void Dispose() cil managed
{
// Unimportant
} // end of method Example::Dispose
Note the attributes on the method: virtual and final. The final is what ensures that you can't override the method in a derived class. Making the interface method implementation behave like a non-virtual method in the language but a virtual one at runtime.
This then also answers your question about early/late binding. It's early, the v-table slot is filled in when the class is loaded.
精彩评论