我试图(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
}
但是,无论我尝试什么,这第二件事都不起作用.所以,请帮忙.
更新
我对支票有一个答案(@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 check if the current property of object1 is of type object2,
how?
您是否尝试使用PropertyDescriptor.PropertyType ?:
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
标签:properties,inner-classes,c 来源: https://codeday.me/bug/20191121/2048168.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。