【问题标题】:Reflection class to get all properties of any object反射类获取任何对象的所有属性
【发布时间】: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


【解决方案1】:

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

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。

【讨论】:

  • 嗨里德,谢谢。我添加了这个,但我仍然得到 0 个属性。我在我的问题中添加了图像,见上文。谢谢!
【解决方案2】:

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

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

【讨论】:

  • 这里注意:成员是任何东西,无论是在类中非静态定义的变量、方法、事件还是属性。成员变量称为“字段”。因此,要么分别查询字段和属性,要么查询所有成员并将其过滤到具有 MemberType 或 MemberTypes.Field 或 MemberType.Property 的成员。
【解决方案3】:

您的 propertyInfos 数组为我的一门课程返回 0 长度。将行更改为

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

导致它被填充。因此,这行代码是你的问题。如果添加标志就会出现

BindingFlags.Instance

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

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

【讨论】:

  • 嗨,上面的代码是我当前的代码。在屏幕截图中,我尝试了 Reed Copsey 的建议。
  • 你能在一个更简单的对象上试试这个代码,看看它是否有效?如果没有,您可以发布您正在尝试的课程的代码吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-24
相关资源
最近更新 更多