简体   繁体   English

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

[英]How does .Net CLR implement an “Interface” internally?

Just curious about how .NET CLR handles interfaces internally? 只是好奇.NET CLR如何在内部处理接口?

Q1] What happens when CLR encounters something like : Q1]当CLR遇到类似的情况时会发生什么:

simple interface example. 简单的界面示例。 (same used below.) (以下同样使用。)

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 : In the above example how are (A) and (B) differentiated ? Q2:在上面的例子中, (A)(B)如何区分?

Q3 : Are Generic Interfaces treated differently? 问题3: 通用接口的处理方式是否不同?

(Feel like a noob when asking basic questions like these ...anyways....) (当问这些基本问题时,感觉就像一个菜鸟......反正....)

Thx all. 大家好。

There are practically no differences in those bits of code. 这些代码位几乎没有差别。 Both end up calling the same function. 两者最终都调用相同的功能。 There may be minor performance benefits in calling the method through the class type. 通过类类型调用方法可能会有一些性能上的好处。

If you want to how these stuff are implemented, have a look at Virtual Method Tables . 如果您想了解这些内容的实现方式,请查看虚拟方法表

For deeper information, see this . 有关更深入的信息,请参阅

Using the interface while creating the object reference is considered a better practice as compared to directly instanciating it with a class type. 与直接使用类类型进行实例化相比,在创建对象引用时使用该接口被认为是更好的做法。 This comes under the programming to an interface principle. 这是对接口原理的编程。

This means you can change the concrete class which implements the same interface at runtime using something like dependency injection or even may be reflection. 这意味着您可以使用依赖注入等方式更改在运行时实现相同接口的具体类,甚至可以是反射。 Your code will not be required to be changed if you program to an interface as compared to programming to an concrete type. 与编程到具体类型相比,如果编程到接口,则不需要更改代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM