Home >Backend Development >C++ >How Can I Retrieve Attribute Information from Class Properties Using Reflection in C#?

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

Linda Hamilton
Linda HamiltonOriginal
2025-01-29 07:52:08930browse

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

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:

  1. Use typeof(Book).GetProperties() to get an array of PropertyInfo objects representing the class's properties.
  2. Iterate through each PropertyInfo object and use GetCustomAttributes() to check for attributes of the desired type (Author in this case).
  3. If an 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn