从C#中的接口创建对象 [英] Creating objects from an interface in C#

查看:62
本文介绍了从C#中的接口创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否仅通过一个接口就可以由此创建对象?

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

类似的东西:

var obj = new IWidget();

(我知道此代码不正确-VS不能创建IWidget的实例)

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

我所处的环境中,我的项目具有对接口的引用,并且我想创建具体的对象并从方法中返回它们-但我无法弄清楚如何仅从接口创建对象./p>

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.

例如:

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

不起作用.

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

会.

无法创建接口,只能创建使用该接口的对象.

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

这篇关于从C#中的接口创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆