将项目添加到列表
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方法并添加项目。
我喜欢这个主意。 – 2009-10-10 03:08:27