reflection类获取任何对象的所有属性

我需要创建一个函数来获取对象的所有属性(包括子对象)这是我的错误记录function。 现在我的代码总是返回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("
"); foreach (PropertyInfo propertyInfo in propertyInfos) { sb.AppendFormat("Name: {0} | Value: {1}
", propertyInfo.Name, "Get Value"); } sb.Append("
"); result = sb.ToString(); } catch (Exception exception) { // to do log it } return result; }

这是对象的样子: 替代文字替代文字

如果您想要所有属性,请尝试:

 propertyInfos = thisObject.GetType().GetProperties( BindingFlags.Public | BindingFlags.NonPublic // Get public and non-public | BindingFlags.Static | BindingFlags.Instance // Get instance + static | BindingFlags.FlattenHierarchy); // Search up the hierarchy 

有关详细信息,请参阅BindingFlags 。

您的代码的问题是PayPal响应类型是成员,而不是属性。 尝试:

 MemberInfo[] memberInfos = thisObject.GetMembers(BindingFlags.Public|BindingFlags.Static|BindingFlags.Instance); 

您的propertyInfos数组为我的一个类返回0长度。 改变行

 propertyInfos = thisObject.GetType().GetProperties(); 

结果在于填充。 因此,这行代码是你的问题。 如果添加标志,则会显示

 BindingFlags.Instance 

对于您的参数,它将返回与无参数调用相同的属性。 将此参数添加到列表中可以解决问题吗?

编辑:刚看到你的编辑。 根据您发布的代码,它也不适用于我。 添加BindingFlags.Instance使它返回我的属性。 我建议您发布您遇到问题的确切代码,因为您的屏幕截图显示了不同的代码。