开发者

Creating objects from an interface in C#

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 canno开发者_如何学JAVAt 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.


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.


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


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.


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


You might be looking for a Dependency Injection framework.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜