"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Dynamically Retrieve Attribute Values from a Class at Runtime?

How Can I Dynamically Retrieve Attribute Values from a Class at Runtime?

Posted on 2025-02-07
Browse:650

How Can I Dynamically Retrieve Attribute Values from a Class at Runtime?

Runtime search attributes

This article introduces a general method for dynamically accessing and extracting property values ​​of a class.

Use special method

Define a common method that accepts type parameters:

public string GetDomainName()
]

Inside the method:

  • Use typeof(T).GetCustomAttributes to retrieve custom attributes:

      var dnAttribute = typeof(T).GetCustomAttributes(
        typeof(DomainNameAttribute), true
      ).FirstOrDefault() as DomainNameAttribute;
  • If the property exists, its value is returned:

      if (dnAttribute != null)
      {
        return dnAttribute.Name;
      }
  • Otherwise, return null:

      return null;
    ]

Utility Extension Method

For broader applicability, generalize this method to handle any attribute:

public static class AttributeExtensions
{
    public static TValue GetAttributeValue(
        this Type type, 
        Func valueSelector) 
        where TAttribute : Attribute
}

Inside the extension method:

  • Retrieve custom properties:

      var att = type.GetCustomAttributes(
        typeof(TAttribute), true
      ).FirstOrDefault() as TAttribute;
  • If the attribute exists, use the provided valueSelector to extract the required value:

    ]
      if (att != null)
      {
        return valueSelector(att);
      }
  • Otherwise, return the default value of this type:

      return default(TValue);
    ]

Usage Example

  • Retrieve DomainName attribute of MyClass:
string name = typeof(MyClass).GetDomainName();
  • Retrieve any attribute value of MyClass using the extension method:
string name = typeof(MyClass)
    .GetAttributeValue((DomainNameAttribute dna) => dna.Name);
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3