Joh*_*han 17 c# generics reflection
可以说我有这门课
class Child {
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Container {
public List<Child> { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我正在研究各种各样的反序列化器,我希望能够Child
从检索到的数据中创建和填充列表.我已经做到这一点了(我已经为这个例子减少了很多其他类型的处理,所以它不必要地"iffy"但是请耐心等待):
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何强制list
转换,List<t.GetType()>
所以我可以访问add方法并添加项目.
Cha*_*ion 19
这应该有效,除非我真的错过了什么.
循环之外
var add = type.GetMethod("Add");
Run Code Online (Sandbox Code Playgroud)
在循环内
add.Invoke(list, new[] { item });
Run Code Online (Sandbox Code Playgroud)