首頁 > 後端開發 > C++ > 如何使用C#中的反射從類屬性中檢索屬性信息?

如何使用C#中的反射從類屬性中檢索屬性信息?

Linda Hamilton
發布: 2025-01-29 07:52:08
原創
899 人瀏覽過

How Can I Retrieve Attribute Information from Class Properties Using Reflection in C#?

>>使用反射訪問c#

中的屬性屬性

>本文演示瞭如何使用C#的反射功能檢索與類屬性關聯的屬性信息。 讓我們考慮帶有Book屬性的Name類,該屬性裝飾有自定義Author屬性。 我們的目標是提取屬性名稱和屬性的值(作者名稱)。

該過程涉及以下步驟:

    >使用
  1. 獲得代表類屬性的typeof(Book).GetProperties()對象的數組。 PropertyInfo
  2. >通過每個
  3. 對象迭代並使用PropertyInfo>檢查所需類型的屬性(在這種情況下為GetCustomAttributes())。 Author如果找到一個
  4. 屬性,請從
  5. 中檢索屬性的名稱,並從屬性實例中獲取屬性的值。 Author PropertyInfo這是一個C#代碼示例,說明了以下內容:

方法返回一個字典,其中鍵是屬性名稱,值是
public class AuthorAttribute : Attribute
{
    public string Name { get; set; }
    public AuthorAttribute(string name) { Name = name; }
}

public class Book
{
    [Author("Jane Austen")]
    public string Name { get; set; }
    // ... other properties
}

public static Dictionary<string, string> GetAuthors()
{
    var authors = new Dictionary<string, string>();
    var properties = typeof(Book).GetProperties();

    foreach (var property in properties)
    {
        var attributes = property.GetCustomAttributes(true);
        foreach (var attribute in attributes)
        {
            var authorAttribute = attribute as AuthorAttribute;
            if (authorAttribute != null)
            {
                authors.Add(property.Name, authorAttribute.Name);
            }
        }
    }
    return authors;
}
登入後複製
>屬性的相應作者名稱。 這有效地說明了反思如何允許訪問與類成員關聯的元數據。

以上是如何使用C#中的反射從類屬性中檢索屬性信息?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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