Filling objects with objects

How can I iterate over the properties of an object and get the value of the property. I have an object that has several properties populated with data. the user indicates which property he wants to view by specifying the name of the property, and I need to find the property in the object and return its value to the user.
 How can I achieve this?
I wrote the following code to get the property, but could not get the value of this prop:

 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();
    }
+3
source share
5 answers

Try this (code is inserted in a line):

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

PropertyInfo, GetValue:) , . , :

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

, , , , . LINQ - , Type.GetProperty, , - .

foreach. , , , null , . , .

+6

pi[i].GetValue(OBJ,null); - , .

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

You call the PropertyInfo.GetValue method passing in the object to get the value.

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

All reflection types, including PropertyInfo, are bound to the class. You must pass an instance of the class to get the data associated with the instance.

0
source

Source: https://habr.com/ru/post/1795485/


All Articles