Creating objects from an interface in C#

2020-08-12 16:36发布

问题:

It is possible, given only an interface, to create an object from this?

Something like:

var obj = new IWidget();

(I know this code isn't right - VS stays cannot create an instance of IWidget)

I'm in a context where my project has references to the interfaces, and I want to create concrete objects and return them from a method - but I can't figure out how to create the objects purely from the interfaces.

回答1:

You can't create an object from an interface. You can create an object from a class that uses that interface.

For example:

IList<string> x = new IList<string>();

will not work.

IList<string> x = new List<string>();

will.

Interfaces cannot be created, only objects that use the interface can be created.



回答2:

That code is actually correct for COM objects, due to compiler wizardry. Normally it's not though.

The problem is, how is the compiler meant to know which implementation to create? There could be any number around. You might want to consider having a factory for the interface, or possibly using dependency injection (e.g. with Spring.NET or Castle Windsor).



回答3:

This will not be possible purely from the interfaces (and shouldn't be, what if there is more than one implementation of it?). It sounds like what you want to do is expose an interface, but not the implementation. Is that correct?

You essentially would want a Factory Pattern. This pattern involves making a method that returns the interface, but internally instantiates a concrete type. It lets you hide the concrete type from anyone using the interface.

If you go a step further you could use Inversion of Control (IoC). I don't know what the best option is for doing this in .Net, but one option is Spring.Net. You use a configuration file to define all of the different setups for your concrete objects, and then have spring automatically "inject" those instances into your classes that use the interface.



回答4:

No would be the short answer. But I guess you could use an IoC container to inject an implemtation.



回答5:

You might be looking for a Dependency Injection framework.



标签: c# .net