将项目添加到List< T>使用反射 [英] Adding items to List<T> using reflection

查看:46
本文介绍了将项目添加到List< T>使用反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过反射将项目添加到IList,但是在调用 Add方法时,抛出了未设置对象引用错误。在调试时,我知道GetMethod( Add)返回的是NULL引用。

I was trying to add items to IList through reflection, but while calling the "Add" method an error was thrown "object ref. not set". While debugging I came to know that the GetMethod("Add") was returning a NULL reference.

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 中而不是在<$ c中找到 Add 方法$ c> List< MyObject> -然后您尝试使用 Type 调用它。

You're trying to find an Add method in Type, not in List<MyObject> - and then you're trying to invoke it on a 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 });

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

(I would also suggest that you start following conventions for variable names, but that's a separate matter.)

这篇关于将项目添加到List&lt; T&gt;使用反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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