且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么C#编译器插入一个显式接口实现?

更新时间:2023-02-14 15:12:17

简短的回答:的CLR要求所有的方法实现接口的方法必须是虚拟( 。ECMA 335分区Ⅱ 12.1节)

Short answer: The CLR requires that all methods that implement an interface method must be virtual (Ecma 335 Partition II Section 12.1).

龙答:


  • 如果在基类中的方法已经是虚拟的,则需要任何额外:接口方法可以绑定到它

  • If the method in the base class is already virtual, then nothing extra is needed: the interface method can be bound to it.

如果在基类中的方法的的虚拟的,但在同一个大会,偷偷摸摸的编译器实际上的使虚拟和最后一个的。反射证实了这一点。 (最终是在C#中密封的CLR术语。)

If the method in the base class is not virtual, but in the same assembly, the sneaky compiler actually makes it virtual and final. Reflector confirms this. ("final" is the CLR terminology for "sealed" in C#.)

如果该在基类中的方法不虚,并在另一个程序集,那么显然编译器不能做到这一点,因为它不能修改的已编译的程序集。因此,这里的唯一选择是插入实现接口方法的重定向方法。如同实现接口方法的所有方法,它也被标记的虚拟和最后一个

If the method in the base class is not virtual and in another assembly, then obviously the compiler can’t do this because it can’t modify the already-compiled assembly. Therefore, the only option here is to insert a redirect method that implements the interface method. Like all methods that implement an interface method, it too is marked virtual and final.

所以回答你的最后一个问题:有没有办法避免这种情况?,不幸的是没有。

So the answer to your last question, "Is there a way to avoid this?", is unfortunately no.