我试图通过反射向IList添加项目,但在调用“Add”方法时,抛出了一个错误“object ref。not set”。在调试时我发现GetMethod(“Add”)返回了一个NULL引用。
Type objTyp = typeof(MyObject); //HardCoded TypeName for demo purpose
var IListRef = typeof (List<>);
Type[] IListParam = {objTyp};
object Result = IListRef.MakeGenericType(IListParam);
MyObject objTemp = new MyObject();
Result.GetType().GetMethod("Add").Invoke(Result, new[] {objTemp });
请帮忙。
答案 0 :(得分:30)
您试图在Add
中找到Type
方法,而不是List<MyObject>
- 然后您尝试在Type
上调用它。
MakeGenericType
返回一个类型,而不是该类型的实例。如果要创建实例,Activator.CreateInstance
通常是要走的路。试试这个:
Type objTyp = typeof(MyObject); //HardCoded TypeName for demo purpose
var IListRef = typeof (List<>);
Type[] IListParam = {objTyp};
object Result = Activator.CreateInstance(IListRef.MakeGenericType(IListParam));
MyObject objTemp = new MyObject();
Result.GetType().GetMethod("Add").Invoke(Result, new[] {objTemp });
(我还建议您开始遵循变量名称的约定,但这是另一回事。)
答案 1 :(得分:3)
private static void Test()
{
IList<Guid> list = CreateList<Guid>();
Guid objTemp = Guid.NewGuid();
list.Add(objTemp);
}
private static List<TItem> CreateList<TItem>()
{
Type listType = GetGenericListType<TItem>();
List<TItem> list = (List<TItem>)Activator.CreateInstance(listType);
return list;
}
private static Type GetGenericListType<TItem>()
{
Type objTyp = typeof(TItem);
var defaultListType = typeof(List<>);
Type[] itemTypes = { objTyp };
Type listType = defaultListType.MakeGenericType(itemTypes);
return listType;
}
IList.Add(对象项目); =&GT;您可以在IList界面中使用Add方法而不是Reflection。
答案 2 :(得分:0)
您只创建了一个泛型类型,但尚未创建该类型的实例。您有一个列表类型,但没有列表。
Result
变量包含Type
个对象,因此Result.Gettype()
返回与typeof(Type)
相同的内容。您正在尝试在Add
课程中找到Type
方法,而不是列表类。
你能否使用泛型而不是反射,例如:
public static List<T> CreateListAndAddEmpty<T>() where T : new() {
List<T> list = new List<T>();
list.Add(new T());
return list;
}