使用反射将项添加到List <T>

Abr*_*mJP 14 c# 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 });
Run Code Online (Sandbox Code Playgroud)

请帮忙.

Jon*_*eet 35

你试图找到一个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 });
Run Code Online (Sandbox Code Playgroud)

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


Doc*_*tor 5

    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;
    }
Run Code Online (Sandbox Code Playgroud)

IList.Add(对象项); => 您可以使用IList接口中的Add方法代替Reflection。