【发布时间】:2013-01-18 23:11:11
【问题描述】:
我正在处理 Reflection ,但是在进行递归时我被卡住了。
代码:
public class User {
public string Name;
public int Number;
public Address Address;
}
public class Address {
public string Street;
public string State;
public string Country;
}
现在我正在打印值。
Type t = user.GetType();
PropertyInfo[] props = t.GetProperties();
foreach (PropertyInfo prp in props)
{
if(!prp.GetType().IsPrimitive && prp.GetType().IsClass)
{
// Get the values of the Inner Class.
// i am stucked over here , can anyone help me with this.
Type ty = prp.GetType();
var prpI = ty.GetProperties();
//var tp = ty.GetType().;
foreach (var propertyInfo in prpI)
{
var value = propertyInfo.GetValue(prp);
var stringValue = (value != null) ? value.ToString() : "";
console.WriteLine(prp.GetType().Name + "." + propertyInfo.Name+" Value : " +stringValue);
}
}
else
{
var value = prp.GetValue(user);
var stringValue = (value != null) ? value.ToString() : "";
console.writeline(user.GetType().Name + "." + prp.Name+" Value : " +stringValue);
}
}
我想知道如何确定属性是类还是原语。如果它是一个类,则进行递归。
【问题讨论】:
-
你为什么不发布一些至少可以编译的东西?
-
你确定反射是问题的解决方案吗?为什么要这样做?
-
你为什么不试试 Automapper 它会做的工作。
-
如果你想以这种方式工作,字典而不是类就可以了。
-
@IamStalker ,Automapper 肯定会工作,但我想自己编写这段代码。所以任何人都可以帮助我找出属性是原始的还是它的类。
标签: c# reflection recursion nested nested-class