简体   繁体   中英

What is the practical use of using interface reference variable in C#?

I know interface reference variable can refer to any object that implements its interface. But what is the practical use of using a reference variable? We can achieve the same by using an object, then why use a reference variable?

The question leaves lots of room for interpretation, but here's mine:

Every object variable is actually a reference variable in C#:

MyClass c = new MyClass();
IMyInterface i = new MyClassThatImplementsInterface();
object o = new object();

All the above are reference variables as they "point" to reference types. I suppose that by your question you mean: Why should I write

IMyInterface i = new MyClassThatImplementsInterface();

instead of

MyClassThatImplementsInterface i = new MyClassThatImplementsInterface();

or even

object i = new MyClassThatImplementsInterface();

Simple answer is: You can call all the methods and properties defined by IMyInterface in the first and second case, and you can not in the last case.

But why not use the second case? Well, this is mostly why people use interfaces at all. Sometimes you don't know the implementing class. Or it is defined internally in some library. All you need to know, however, is that when you call a method you get some object in return that conforms to the interface you know. So that's all you need (and sometimes that's also all you get).

For example:
I've recently created an application that can display modules defined in plugin DLLs, which are dynamically loaded by a launcher application. The launcher application adds buttons for each plugin and changes the UI when a plugin button is pressed.

The launcher application knows nothing about the plugins - apart from one interface that contains properties returning titles, icons, a UserControl for the UI, etc.

I don't have any classes I can work with. All there is is a factory class that returns an instance of an object that implements my interface. And that's all you need to have.

Lets say we have an interface IRenderPage, now rendering of page may vary from device to device, you can have a common reference pointing to diffrent implementations.

This is why we have interface, a contract to be fulfilled by implementing class, and the classes implementing this interface can participate in defined set of processes with there own implementation.

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