[英]How to add an object to a generic list property of an instance of a class using reflection
I have a class structure below. 我下面有一个班级结构。 I am getting this error.
我收到了这个错误。 Am i missing something here?
我错过了什么吗?
Object does not match target type.
对象与目标类型不匹配。
Class Structure 阶级结构
public class Schedule
{
public Schedule() { Name = ""; StartDate = DateTime.MinValue; LectureList = new List<Lecture>(); }
public string Name { get; set; }
public DateTime StartDate { get; set; }
public List<Lecture> LectureList { get; set; }
}
public class Lecture
{
public string Name { get; set; }
public int Credit { get; set; }
}
What i am trying: 我在想什么:
Schedule s = new Schedule();
Type t = Type.GetType("Lecture");
object obj = Activator.CreateInstance(t);
obj.GetType().GetProperty("Name").SetValue(obj, "Math");
obj.GetType().GetProperty("Credit").SetValue(obj, 1);
PropertyInfo pi = s.GetType().GetProperty("LectureList");
Type ti = Type.GetType(pi.PropertyType.AssemblyQualifiedName);
ti.GetMethod("Add").Invoke(pi, new object[] { obj });
It should be something like this: 它应该是这样的:
// gets metadata of List<Lecture>.Add method
var addMethod = pi.PropertyType.GetMethod("Add");
// retrieves current LectureList value to call Add method
var lectureList = pi.GetValue(s);
// calls s.LectureList.Add(obj);
addMethod.Invoke(lectureList, new object[] { obj });
The problem is that you get the Add
method of List<Lecture>
and try to invoke it with PropertyInfo
as the instance invoking the method. 问题是您获得了
List<Lecture>
的Add
方法,并尝试使用PropertyInfo
作为调用该方法的实例来调用它。
Change: 更改:
ti.GetMethod("Add").Invoke(pi, new object[] { obj });
to: 至:
object list = pi.GetValue(s);
ti.GetMethod("Add").Invoke(list, new object[] { obj });
That way pi.GetValue(s)
gets the List<Lecture>
itself from the PropertyInfo
(which only represents the property itself along with its get
and set
methods, and invoke its Add
method with your object[]
as arguments. 这样,
pi.GetValue(s)
从PropertyInfo
获取List<Lecture>
本身(它仅表示属性本身及其get
和set
方法,并以object[]
作为参数调用其Add
方法。
One more thing. 还有一件事。 why using:
为何使用:
Type ti = Type.GetType(pi.PropertyType.AssemblyQualifiedName);
When you can just use: 什么时候可以使用:
Type ti = pi.PropertyType;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.