代码之家  ›  专栏  ›  技术社区  ›  Amitd

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

  •  6
  • Amitd  · 技术社区  · 16 年前

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

    Q1]当CLR遇到以下情况时会发生什么情况:

    simple interface example. (如下所示。)

    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();
    
            }
        }
    

    (一) 差异化?

    问题3:是 Generic Interfaces 区别对待?

    全部。

    2 回复  |  直到 16 年前
        1
  •  2
  •   Gorkem Pacaci    16 年前

    在这些代码位上几乎没有差别。两者最终都调用同一个函数。通过类类型调用方法可能会带来一些性能上的小好处。

    如果你想知道这些东西是如何实现的,看看 Virtual Method Tables

    有关详细信息,请参见 this .

        2
  •  -5
  •   Nilesh Gule    16 年前

    这意味着您可以更改具体的类,该类在运行时使用类似于依赖注入甚至可能是反射的方法实现相同的接口。如果编程到接口,而不是编程到具体类型,则不需要更改代码。