使用反射初始化嵌套复杂类型
代码树就像:
Class Data
{
List<Primitive> obj;
}
Class A: Primitive
{
ComplexType CTA;
}
Class B: A
{
ComplexType CTB;
Z o;
}
Class Z
{
ComplexType CTZ;
}
Class ComplexType { .... }
现在在 List
中,有许多类的 ComplexType
对象为“null”。我只是想将其初始化为某个值。
问题是如何使用反射来遍历完整的树。
编辑:
Data data = GetData(); //All members of type ComplexType are null.
ComplexType complexType = GetComplexType();
我需要将“data”中的所有“ComplexType”成员初始化为“complexType”
Code tree is like:
Class Data
{
List<Primitive> obj;
}
Class A: Primitive
{
ComplexType CTA;
}
Class B: A
{
ComplexType CTB;
Z o;
}
Class Z
{
ComplexType CTZ;
}
Class ComplexType { .... }
Now in List<Primitive> obj
, there are many classes in which ComplexType
object is 'null'. I just want to initialize this to some value.
The problem is how to traverse the complete tree using reflection.
Edit:
Data data = GetData(); //All members of type ComplexType are null.
ComplexType complexType = GetComplexType();
I need to initialize all 'ComplexType' members in 'data' to 'complexType'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我理解正确的话,也许像这样的东西会起作用:
并且这个方法将被称为:
这个代码当然只适用于字段。如果您还需要属性,则必须让循环遍历所有属性(可以通过
instance.GetType().GetProperties(...)
检索)。但请注意,这种反射并不是特别有效。
If I understand you correctly perhaps something like this would do the trick:
And this method would be called like:
This code only works for fields of course. If you want properties as well you would have to have the loop iterate through all properties (which can be retreived by
instance.GetType().GetProperties(...)
).Be aware though that reflection is not particularly efficient.