【问题标题】:Looping through Objects properties循环遍历对象属性
【发布时间】:2011-03-01 13:04:46
【问题描述】:

如何遍历对象的属性并获取属性的值。
我有一个对象,它有几个属性填充数据。用户通过提供属性名称来指定他想要查看的属性,我需要在对象中搜索该属性并将其值返回给用户。
我怎样才能做到这一点?
我编写了以下代码来获取属性,但无法获取该属性的值:

 public object FindObject(object OBJ, string PropName)
    {
        PropertyInfo[] pi = OBJ.GetType().GetProperties();
        for (int i = 0; i < pi.Length; i++)
        {
            if (pi[i].PropertyType.Name.Contains(PropName))
                return pi[i];//pi[i] is the property the user is searching for,
                             // how can i get its value?
        } 
        return new object();
    }

【问题讨论】:

标签: c#


【解决方案1】:

试试这个(内嵌代码):

public object FindObject(object OBJ, string PropName)
{
    PropertyInfo[] pi = OBJ.GetType().GetProperties();
    for (int i = 0; i < pi.Length; i++)
    {
        if (pi[i].PropertyType.Name.Contains(PropName))
        {
            if (pi[i].CanRead)                     //Check that you can read it first
               return pi[i].GetValue(OBJ, null);   //Get the value of the property
        }
    }
    return new object();
}

【讨论】:

    【解决方案2】:

    要从PropertyInfo 中获取值,请调用GetValue :) 我怀疑您真的想得到属性的名称​​type你。我怀疑你想要:

    if (pi[i].Name == PropName)
    {
        return pi[i].GetValue(OBJ, null);
    }
    

    请注意,您可能应该确保该属性不是索引器,并且是可读和可访问的等。LINQ 是一种过滤事物的好方法,或者您可以使用Type.GetProperty 直接访问该属性所需的名称,而不是循环 - 并且 then 执行您需要的所有验证。

    您还应该考虑遵循命名约定并使用foreach 循环。哦,如果找不到该属性,我可能会返回 null 或抛出异常。我看不出返回一个新的空对象是个好主意。

    【讨论】:

      【解决方案3】:

      pi[i].GetValue(OBJ,null); 是要使用的函数。

      【讨论】:

        【解决方案4】:
        public static object FindObject(object obj, string propName)
        {
            return obj.GetType().GetProperties()
                .Where(pi => pi.Name == propName && pi.CanRead)
                .Select(pi => pi.GetValue(obj, null))
                .FirstOrDefault();
        }
        

        【讨论】:

          【解决方案5】:

          您调用PropertyInfo.GetValue 方法传入对象以获取其值。

          public object FindObject(object OBJ, string PropName)      
          {          
              PropertyInfo[] pi = OBJ.GetType().GetProperties();           
          
              for (int i = 0; i < pi.Length; i++)           
              {               
                  if (pi[i].Name == PropName)                   
                  {
                      return pi[i].GetValue(OBJ, null);
                  }
              }            
          
              return new object();       
          }   
          

          所有反射类型,包括 PropertyInfo 都绑定到类。您必须传入类的实例才能获取任何与实例相关的数据。

          【讨论】:

            猜你喜欢
            • 2014-01-26
            • 2021-11-20
            • 2016-09-09
            • 2014-12-19
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多