【发布时间】:2010-10-26 01:23:20
【问题描述】:
我需要创建一个函数来获取对象的所有属性(包括子对象)这是我的错误记录功能。 现在我的代码总是返回 0 个属性。 请让我知道我做错了什么,谢谢!
public static string GetAllProperiesOfObject(object thisObject)
{
string result = string.Empty;
try
{
// get all public static properties of MyClass type
PropertyInfo[] propertyInfos;
propertyInfos = thisObject.GetType().GetProperties(BindingFlags.Public | BindingFlags.Static);//By default, it will return only public properties.
// sort properties by name
Array.Sort(propertyInfos,
(propertyInfo1, propertyInfo2) => propertyInfo1.Name.CompareTo(propertyInfo2.Name));
// write property names
StringBuilder sb = new StringBuilder();
sb.Append("<hr />");
foreach (PropertyInfo propertyInfo in propertyInfos)
{
sb.AppendFormat("Name: {0} | Value: {1} <br>", propertyInfo.Name, "Get Value");
}
sb.Append("<hr />");
result = sb.ToString();
}
catch (Exception exception)
{
// to do log it
}
return result;
}
这是对象的样子:
【问题讨论】:
-
那些(IPAddress、MerchantSessionId 等)是属性,而不是字段,对吧?
-
里德,我不确定。但是我有兴趣获取所有字段和属性。包括任何子对象。
标签: c# reflection