繁体   English   中英

将项目添加到列表 <T> 使用反射

[英]Adding items to List<T> using reflection

我试图通过反射向IList添加项目,但在调用“添加”方法时,抛出错误“对象引用未设置”。 在调试时我发现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 });

请帮忙。

您试图在Type找到Add方法,而不是在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 });

(我还建议您开始遵循变量名称的约定,但这是另一回事。)

    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(对象项); =>您可以在IList接口中使用Add方法而不是Reflection。

您只创建了一个泛型类型,但尚未创建该类型的实例。 您有一个列表类型,但您没有列表。

Result变量包含一个Type对象,因此Result.Gettype()返回与typeof(Type)相同的值。 您正在尝试在Type类中找到Add方法,而不是列表类。

你能否使用泛型而不是反射,例如:

public static List<T> CreateListAndAddEmpty<T>() where T : new() {
  List<T> list = new List<T>();
  list.Add(new T());
  return list;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM