.Net CLR如何在内部实现“接口”?

只是好奇.NET CLR如何在内部处理接口?

Q1]当CLR遇到类似的情况时会发生什么:

简单的界面示例。 (以下同样使用。)

interface ISampleInterface { void SampleMethod(); } class ImplementationClass : ISampleInterface { // Explicit interface member implementation: public void SampleMethod() { // Method implementation. } static void Main() { //Declare an interface instance. ISampleInterface mySampleIntobj = new ImplementationClass(); // (A) // Call the member. mySampleIntobj.SampleMethod(); // Declare an interface instance. ImplementationClass myClassObj = new ImplementationClass(); // (B) //Call the member. myClassObj.SampleMethod(); } } 

Q2:在上面的例子中, (A)(B)如何区分?

问题3: 通用接口的处理方式是否不同?

(当问这些基本问题时,感觉就像一个菜鸟……反正….)

大家好。

这些代码位几乎没有差别。 两者最终都调用相同的function。 通过类类型调用方法可能会有一些性能上的好处。

如果您想了解这些内容的实现方式,请查看虚拟方法表 。

有关更深入的信息,请参阅此

与直接使用类类型进行实例化相比,在创建对象引用时使用接口被认为是更好的做法。 这是针对接口原理的编程。

这意味着您可以使用dependency injection等方式更改在运行时实现相同接口的具体类,甚至可以是reflection。 与编程到具体类型相比,如果编程到接口,则不需要更改代码。