Home >Backend Development >C++ >How Can Reflection Retrieve Property Values from Strings in C#?
Leveraging C# Reflection to Access Property Values from Strings
Reflection in C# provides a dynamic way to interact with objects at runtime. A common application is retrieving property values when you only have their names as strings.
This technique is particularly useful when dealing with dynamic data or configurations where property names are not known at compile time.
Utilizing Type.GetProperty()
and GetValue()
The core of this approach lies in the Type.GetProperty()
and GetValue()
methods. Here's a concise function demonstrating this:
<code class="language-csharp">public static object GetPropertyValue(object obj, string propertyName) { Type type = obj.GetType(); PropertyInfo property = type.GetProperty(propertyName); return property?.GetValue(obj); }</code>
This function takes an object and a property name (as a string) and returns the property's value. The null-conditional operator (?.
) gracefully handles cases where the property doesn't exist, preventing exceptions.
Practical Example
Let's illustrate its usage:
<code class="language-csharp">public class MyClass { public string MyProperty { get; set; } } // ... later in your code ... string className = "MyClass"; string propertyName = "MyProperty"; object instance = Activator.CreateInstance(Type.GetType(className)); object propertyValue = GetPropertyValue(instance, propertyName); </code>
This example dynamically creates an instance of MyClass
and retrieves the value of MyProperty
using the GetPropertyValue
function. This eliminates the need for hardcoded property access and enhances code flexibility.
The above is the detailed content of How Can Reflection Retrieve Property Values from Strings in C#?. For more information, please follow other related articles on the PHP Chinese website!