创建使用反射通用的IList实例 [英] Creating a generic IList instance using reflection

查看:179
本文介绍了创建使用反射通用的IList实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个使用反射对象的泛型列表。下面code抛出一个错误的无法创建接口的实例。。我可以改变IList中列出,它工作正常,但我想知道是否有办法让这个工作有一个IList。

 变数名称= typeof运算(IList的< T>)AssemblyQualifiedName。    类型type = Type.GetType(名);    VAR列表= Activator.CreateInstance(类型);


解决方案

你必须instatiate一个具体的类,所以,如果你做

  VAR类型= Type.GetType(typeof运算(列表< T>)AssemblyQualifiedName);
VAR名单=(IList的< T>)Activator.CreateInstance(类型);

您会succesfull(只要您为当然吨有效值)。

I am trying to create a generic list of objects using reflection. The below code throws an error Cannot create an instance of an interface. . I could change the IList to List and it works fine, but I was wondering if there is way to get this working with an IList.

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

    Type type = Type.GetType(name);

    var list = Activator.CreateInstance(type);

解决方案

you'll have to instatiate a concrete class so if you do

var type = Type.GetType(typeof (List<T>).AssemblyQualifiedName);
var list = (Ilist<T>)Activator.CreateInstance(type);

you will be succesfull (as long as you supply a valid value for T of course).

这篇关于创建使用反射通用的IList实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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