简体   繁体   中英

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

Just curious about how .NET CLR handles interfaces internally?

Q1] What happens when CLR encounters something like :

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 ?

Q3 : Are Generic Interfaces treated differently?

(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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