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(); }
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(); }
PropertyInfo, GetValue:) , . , :
PropertyInfo
GetValue
if (pi[i].Name == PropName) { return pi[i].GetValue(OBJ, null); }
, , , , . LINQ - , Type.GetProperty, , - .
Type.GetProperty
foreach. , , , null , . , .
foreach
pi[i].GetValue(OBJ,null); - , .
pi[i].GetValue(OBJ,null);
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(); }
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.
Source: https://habr.com/ru/post/1795485/More articles:iPhone SDK: How to check if the IP address is actually entered by the user? - objective-cКак я могу нарисовать точку или линию на карте в j2me? - google-maps-api-3Adding and removing items dynamically in the same view with Entity Framework and MVC - asp.netIPhone files are not resistant - c #How do I iterate over multiple files while maintaining the base name for further processing? - bashIntercepting installed applications on an Android device - javaJava ListSelectionListener double-change value - javaclear data from a shared privilege in an android - android applicationIs it possible to connect an anonymous delegate using reflection? - reflectionhow many times is the line of code executed when the program starts? - pythonAll Articles