【发布时间】:2009-10-10 03:00:43
【问题描述】:
假设我有这门课
class Child {
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Container {
public List<Child> { get; set; }
}
我正在开发一种反序列化器,我希望能够从检索到的数据中创建和填充Child 列表。我已经做到了这一点(我已经为这个例子减少了很多其他类型的处理,所以它不必要地“不确定”但请耐心等待):
var props = typeof(Container).GetProperties();
foreach (var prop in props) {
var type = prop.PropertyType;
var name = prop.Name;
if (type.IsGenericType) {
var t = type.GetGenericArguments()[0];
if (type == typeof(List<>)) {
var list = Activator.CreateInstance(type);
var elements = GetElements();
foreach (var element in elements) {
var item = Activator.CreateInstance(t);
Map(item, element);
// ??? how do I do list.Add(item) here?
}
prop.SetValue(x, list, null); // x is an instance of Container
}
}
}
我不知道如何将list 转换为本质上的List<t.GetType()>,因此我可以访问 add 方法并添加项目。
【问题讨论】:
标签: c# generics reflection