遍历对象属性

3

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

 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();
    }

可能是 https://dev59.com/603Sa4cB1Zd3GeqPvn0V 的重复问题。 - Gabe
5个回答

8
尝试以下方法(代码内嵌):
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();
}

6
要从PropertyInfo中获取值,您需要调用GetValue :) 我怀疑您真的想要获取属性类型的名称。我猜您想要:
if (pi[i].Name == PropName)
{
    return pi[i].GetValue(OBJ, null);
}

请注意,您应该确保属性不是索引器,并且是可读和可访问的等。LINQ 是过滤内容的好方法,或者您可以直接使用 Type.GetProperty 来获取所需名称的属性,而不是循环 - 然后执行所有需要的验证。
您还应考虑遵循命名约定并使用 foreach 循环。哦,如果找不到属性,我可能会返回 null 或抛出异常。我无法想象返回一个新的空对象是个好主意。

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

1
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();
}

0

您调用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 都绑定到类。您必须传入类的实例才能获取任何与实例相关的数据。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接