首頁 > 後端開發 > C++ > 反射如何從C#中的字符串中檢索屬性值?

反射如何從C#中的字符串中檢索屬性值?

Susan Sarandon
發布: 2025-02-02 19:31:11
原創
768 人瀏覽過

How Can Reflection Retrieve Property Values from Strings in C#?

>利用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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板