如何通过反射创建一个类型列表

3
我有一段代码长这样:

我有一段代码长这样:

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。

任何帮助都将不胜感激!

3个回答

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

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

您可以尝试将对象强制转换为 IList 类型并直接调用 Add 方法,而无需使用反射查找方法:
var list = (IList)Activator.CreateInstance(listType);
list.Add(x);

2

试试这个:

var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(myType);

var myList = (IList)Activator.CreateInstance(constructedListType);
myList.Add(x);

列表不会是强类型的,但您可以将项目作为对象添加。

1
你需要使用 MakeGenericType 方法:
var argument = new Type[] { typeof(myType) };
var listType = typeof(List<>); 
var genericType = listType.MakeGenericType(argument); // create generic type
var instance = Activator.CreateInstance(genericType);  // create generic List instance

var method = listType.GetMethod("Add"); // get Add method
method.Invoke(instance, new [] { argument }); // invoke add method 

或者您可以将实例转换为 IList 并直接使用 Add 方法。或者使用 dynamic 类型,无需担心转换:

dynamic list = Activator.CreateInstance(genericType);
list.Add("bla bla bla...");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接