Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用反射创建通用IList实例_C#_Asp.net_Reflection - Fatal编程技术网

C# 使用反射创建通用IList实例

C# 使用反射创建通用IList实例,c#,asp.net,reflection,C#,Asp.net,Reflection,我正在尝试使用反射创建对象的通用列表。下面的代码抛出错误无法创建接口实例。。我可以将IList更改为List,它工作得很好,但我想知道是否有办法让它与IList一起工作 var name = typeof (IList<T>).AssemblyQualifiedName; Type type = Type.GetType(name); var list = Activator.CreateInstance(type); var name=typeof(I

我正在尝试使用反射创建对象的通用列表。下面的代码抛出错误无法创建接口实例。。我可以将IList更改为List,它工作得很好,但我想知道是否有办法让它与IList一起工作

    var name = typeof (IList<T>).AssemblyQualifiedName;

    Type type = Type.GetType(name);

    var list = Activator.CreateInstance(type);
var name=typeof(IList).AssemblyQualifiedName;
Type Type=Type.GetType(名称);
var list=Activator.CreateInstance(类型);

方法调用默认构造函数来创建作为参数传递的类型的实例。这个类型必须是非抽象的,不是接口的,并且有一个默认的构造函数才能使这个函数成功。

不,这是不可能的。错误信息非常清楚。不能创建接口的实例

它如何知道您想要哪个特定类的实例?通常,许多类实现相同的接口。它应该只是随便挑一个吗?;-)


这与反射无关,因为您也无法正常地“实例化”接口。只分配实现接口的对象,然后传递接口引用。

不,不可能创建接口实例

NET(或者更确切地说是Activator.CreateInstance方法)应该如何决定应该实例化该接口的哪个实现

你不能这样做:

IList<int> l = new IList<int>();
IList l=新IList();
你也可以吗?
你不能实例化一个接口,因为接口实际上是一个定义或契约,它描述了一个类型应该实现哪些功能。

我认为你无法实现这个功能,因为你不知道你需要创建什么类型的对象


抽象类也会有同样的问题。

显然,不能直接实例化
IList
类型的对象,因为它是接口类型


您应该尝试实例化一个
列表
,然后可能会将其作为
IList
返回,您将不得不建立一个具体的类,因此如果您这样做的话

var type = Type.GetType(typeof (List<T>).AssemblyQualifiedName);
var list = (Ilist<T>)Activator.CreateInstance(type);
var type=type.GetType(typeof(List).AssemblyQualifiedName);
var list=(Ilist)Activator.CreateInstance(类型);
您将成功(当然,只要您为T提供有效值)。

IList Create()
{
类型baseListType=typeof(列表);
Type listType=baseListType.MakeGenericType(typeof(T));
将Activator.CreateInstance(listType)返回为IList;
}

好吧,你可以用C#实例化一个接口。但前提是你真的告诉它怎么做

看和

然而,在您的例子中,似乎您误解了接口的工作方式


只需创建一个列表,然后返回一个IList,您的调用代码就不会在意您是否实际使用了列表。

您的代码段有错误。typeof(int)应该是typeof(T)。您应该尝试编译并运行它。我没有,但我也不需要说这是错的。修正它,我就修正投票typeof(IList)返回与第二行中表达式相同的类型(type.GetType(name);),换句话说,当您需要系统时,只需执行var type=typeof(sometype)。该特定类型的type对象不能执行以下操作:var list=(IList)Activator.CreateInstance(typeof(list))???是的,你可以,我走了很长的路使它更接近OPs片段
IList<T> Create<T>()
{
    Type baseListType = typeof(List<>);
    Type listType = baseListType.MakeGenericType(typeof(T));
     return Activator.CreateInstance(listType) as IList<T>;
}