且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-17 18:54:20

您正在尝试在 Type 中而不是在 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.)