我试图(1)记录对象的所有属性,以及(2)其中特定对象类型的所有属性。我可以做(1)但不能做(2)。
现在就是这种情况。
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(object1))
{
string name = descriptor.Name;
object value = descriptor.GetValue(object1);
logger.Debug(String.Format("{0} = {1}", name, value));
}
我需要的是这样的:
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(object1))
{
string name = descriptor.Name;
object value = descriptor.GetValue(object1);
logger.Debug(String.Format("{0} = {1}", name, value));
// TODO check if the current property of object1 is of type object2, how?
if (...) {
// TODO repeat the process for object2
foreach (PropertyDescriptor innerdescriptor in TypeDescriptor.GetProperties(object2))
{
string innername = innerdescriptor.Name;
object innervalue = innerdescriptor.GetValue(object2);
logger.Debug(String.Format(" {0} = {1}", innername, innervalue));
}
} // end if
}
然而,无论我如何尝试,第二件事都不起作用。所以,请帮忙。
update我有支票的答案(@Alex Art.)
if (descriptor.PropertyType == typeof(the type that you expecting) ) { ... }
现在唯一剩下的就是内部对象属性记录器!
我认为可以通过使用反射来实现(但你应该意识到性能损失):
public void LogProps(Object object1)
{
var objType = object1.GetType();
IList<PropertyInfo> properties = new List<PropertyInfo>(objType.GetProperties());
foreach (PropertyInfo prop in properties)
{
var propValue = prop.GetValue(object1, null);
if(prop.PropertyType == typeof(yourTypeHere))
{
LogProps(propValue);
}
else
{
logger.Debug(String.Format("{0} = {1}", prop.Name, propValue));
}
}
}
我还在这里使用了递归,如果您有一些很长的层次结构,这也可能会出现问题
关于您的解决方案:
// TODO 检查 object1 的当前属性是否属于 object2 类型,
如何?
你尝试过使用PropertyDescriptor.PropertyType http://msdn.microsoft.com/en-us/library/system.componentmodel.propertydescriptor.propertytype(v=vs.110).aspx?:
object value = descriptor.GetValue(object1);
if (descriptor.PropertyType == typeof(the type that you expecting) )
{
foreach (PropertyDescriptor innerdescriptor in TypeDescriptor.GetProperties(value)
{
string innername = innerdescriptor.Name;
object innervalue = innerdescriptor.GetValue(object2);
logger.Debug(String.Format(" {0} = {1}", innername, innervalue));
}
} // end if
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)