>利用C#反射从字符串访问属性值
> C#中的反射提供了一种在运行时与对象交互的动态方法。 一个常见的应用程序是在您只有其名称作为字符串时检索属性值。>
在处理动态数据或配置时,此技术特别有用,而在编译时间不知道属性名称。 >利用和Type.GetProperty()
GetValue()
和Type.GetProperty()
>方法。 这是一个简明的功能,证明了这一点:GetValue()
<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>此功能以对象和属性名称(作为字符串)返回属性的值。 null条件运算符(
)优雅地处理不存在该属性的情况,以防止异常。?.
实践
让我们说明其用法:
<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>这个示例动态创建了一个
的实例,并使用MyClass
>函数检索MyProperty
>的值。 这消除了对硬编码属性访问的需求,并增强了代码灵活性。GetPropertyValue
>
以上是反射如何从C#中的字符串中检索属性值?的详细内容。更多信息请关注PHP中文网其他相关文章!