gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:15:15 25 4
gpt4 key购买 nike

我在下面有一个类结构。我收到此错误。我在这里遗漏了什么吗?

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

更新。这是 fiddle link .

关于c# - 如何使用反射将对象添加到类实例的通用列表属性中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39161851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com