编程语言
首页 > 编程语言> > c# – 如何使用反射将对象添加到类的实例的泛型列表属性中

c# – 如何使用反射将对象添加到类的实例的泛型列表属性中

作者:互联网

我下面有一个班级结构.我收到了这个错误.我错过了什么吗?

Object does not match target type.

阶级结构

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; }
}

我在想什么:

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 });

解决方法:

它应该是这样的:

// 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 });

UPD.这是小提琴link.

标签:c,net,reflection,generic-list,mscorlib
来源: https://codeday.me/bug/20190623/1267803.html