如何创建从反射获得的类型列表 [英] how to create a list of type obtained from reflection

查看:67
本文介绍了如何创建从反射获得的类型列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的代码:

I have a code which looks like this :

Assembly assembly = Assembly.LoadFrom("ReflectionTest.dll");
Type myType = assembly.GetType(@"ReflectionTest.TestObject");
var x = Convert.ChangeType((object)t, myType);   

//List<myType> myList = new List<myType>();
//myList.Add(x);

代码的注释部分就是我被卡住的地方。我从服务中获取了一些对象,并且转换也很好。我正在尝试填充此类对象的列表,然后将其绑定到WPF DataGrid。

The commented part of the code is where I am stuck. I am getting some objects from a service and the conversion works fine too. I am trying to populate a list of such objects and will later bind to WPF DataGrid.

感谢任何帮助!

推荐答案

var listType = typeof(List<>).MakeGenericType(myType)
var list = Activator.CreateInstance(listType);

var addMethod = listType.GetMethod("Add");
addMethod.Invoke(list, new object[] { x });

您也许可以转换为 IList 并直接调用 Add 而不是通过反射查找方法:

You might be able to cast to IList and call Add directly instead of looking up the method with reflection:

var list = (IList)Activator.CreateInstance(listType);
list.Add(x);

这篇关于如何创建从反射获得的类型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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