In C#, a common scenario arises where one needs to dynamically access the value of a property of an object based on its name. This can be useful for generic programming or reflection-based scenarios.
To achieve this, you can leverage the Reflection capabilities of .NET. Here's how:
public string GetPropertyValue(string propertyName) { // Retrieve the type of the object Type type = car.GetType(); // Obtain the property information based on its name PropertyInfo property = type.GetProperty(propertyName); // Invoke the `GetValue` method to retrieve the property value object value = property.GetValue(car, null); // Return the property value as a string return value.ToString(); }
In this method:
Using this method for the car object with the property name "Make," it will return the value "Ford." This approach allows for flexible and dynamic property value retrieval in C#.
The above is the detailed content of How to Dynamically Retrieve Property Values by Name in C#?. For more information, please follow other related articles on the PHP Chinese website!