>利用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>
)優雅地處理不存在該屬性的情況,以防止異常。 ?.
實踐
讓我們說明其用法:
<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中文網其他相關文章!