IL 中如何实现显式接口实现?

发布于 2024-09-10 07:48:03 字数 520 浏览 4 评论 0原文

我一直在研究 IL 中的显式接口实现。以下类中的方法 Method(接口 IA 上有一个 Method()):

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

被编译为以下 IL 方法签名:

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

我的问题是 - 为什么 IL 中的方法名称是 IA.Method(),而不是直接的 Method?这实际上意味着什么?如果错过了,为什么它不起作用?我在 ECMA 规范或 google 中找不到任何相关内容。

I've been having a look at explicit interface implementations in IL. The method Method in the following 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦明 2024-09-17 07:48:03

这是因为这样你就可以多次拥有一个方法。

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

第一种是常规方法。其次是接口的实现。如果没有前缀,您就无法同时拥有两者,因为您无法区分它们。

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

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
月依秋水 2024-09-17 07:48:03

这是您要查找的文档:
http://msdn.microsoft.com/en-us/library/ms173157。 aspx

这样做的原因是为了处理这种情况:

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

如果您有两个想要实现的具有相同签名的方法,则需要一些东西来使它们不同,以便您可以提供单独的实现。接口的名称提供了这一点。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文