开发者

How are explicit interface implementations implemented in IL?

I've been having a look at explicit interface implementations in IL. The method Method in the fo开发者_高级运维llowing class (interface IA has a single Method() on it):

public class B : IA
    object IA.Method() {
        /* code */
    }
}

is compiled to the following IL method signature:

.method private hidebysig newslot virtual final instance object IA.Method() cil managed {
    .override IA::Method
    /* code */
}

My question is - why is the method name in IL IA.Method(), rather than just straight Method? What does this actually mean, and why doesn't it work if it's missed off? I can't find anything in the ECMA spec or google about it.


This is because this way you can have a method multiple times.

public class B : IA
{
    object Method() {    }
    object IA.Method() {    }
}

The first is a normal method. The second is the interface implementation. Without the prefix you could not have both because you could not differentiate between them.

new B().Method(); // calls the normal method
((IA)new B()).Method(); // calls the IA interface method


Here's the documentation you're looking for:
http://msdn.microsoft.com/en-us/library/ms173157.aspx

The reason for it is to handle this case:

public class C : IA, IB
{
    object IA.Method()
    { 
        // Implementation!
    } 
    object IB.Method()
    { 
        // Implementation!
    } 
}

If you've got two methods with the same signature that you want to implement, you need something to make them different so you can supply seperate implementations. The name of the interface provides that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜