Using Reflection to Access Property Attributes in C#
This article demonstrates how to retrieve attribute information associated with class properties using C#'s reflection capabilities. Let's consider a Book
class with a Name
property decorated with a custom Author
attribute. Our goal is to extract both the property name and the attribute's value (author name).
The process involves these steps:
typeof(Book).GetProperties()
to get an array of PropertyInfo
objects representing the class's properties.PropertyInfo
object and use GetCustomAttributes()
to check for attributes of the desired type (Author
in this case).Author
attribute is found, retrieve the property's name from PropertyInfo
and the attribute's value from the attribute instance.Here's a C# code example illustrating this:
<code class="language-csharp">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; }</code>
This GetAuthors()
method returns a dictionary where keys are property names and values are the corresponding author names from the Author
attribute. This effectively demonstrates how reflection allows access to metadata associated with class members.
The above is the detailed content of How Can I Retrieve Attribute Information from Class Properties Using Reflection in C#?. For more information, please follow other related articles on the PHP Chinese website!