>>使用反射訪問c#
中的屬性屬性>本文演示瞭如何使用C#的反射功能檢索與類屬性關聯的屬性信息。 讓我們考慮帶有Book
屬性的Name
類,該屬性裝飾有自定義Author
屬性。 我們的目標是提取屬性名稱和屬性的值(作者名稱)。
typeof(Book).GetProperties()
對象的數組。 PropertyInfo
PropertyInfo
>檢查所需類型的屬性(在這種情況下為GetCustomAttributes()
)。
Author
如果找到一個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中文網其他相關文章!