Home >Backend Development >C++ >How Can I Dynamically Retrieve Attribute Values from a Class at Runtime?

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

Linda Hamilton
Linda HamiltonOriginal
2025-01-12 06:04:12896browse

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

Retrieve properties at runtime

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

Use dedicated methods

Define a generic method that accepts type parameters:

<code class="language-csharp">public string GetDomainName<T>()</code>

Internal method:

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

    <code class="language-csharp">  var dnAttribute = typeof(T).GetCustomAttributes(
        typeof(DomainNameAttribute), true
      ).FirstOrDefault() as DomainNameAttribute;</code>
  • If the attribute exists, return its value:

    <code class="language-csharp">  if (dnAttribute != null)
      {
        return dnAttribute.Name;
      }</code>
  • Otherwise, return null:

    <code class="language-csharp">  return null;</code>

Utility extension methods

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

<code class="language-csharp">public static class AttributeExtensions
{
    public static TValue GetAttributeValue<TAttribute, TValue>(
        this Type type, 
        Func<TAttribute, TValue> valueSelector) 
        where TAttribute : Attribute
}</code>

Internal extension method:

  • Retrieve custom attributes:

    <code class="language-csharp">  var att = type.GetCustomAttributes(
        typeof(TAttribute), true
      ).FirstOrDefault() as TAttribute;</code>
  • If the attribute exists, use the provided valueSelector to extract the required value:

    <code class="language-csharp">  if (att != null)
      {
        return valueSelector(att);
      }</code>
  • Otherwise, return the default value of the type:

    <code class="language-csharp">  return default(TValue);</code>

Usage examples

  • Retrieve the MyClass attribute of DomainName:
<code class="language-csharp">string name = typeof(MyClass).GetDomainName<MyClass>();</code>
  • Retrieve any attribute value of MyClass using extension methods:
<code class="language-csharp">string name = typeof(MyClass)
    .GetAttributeValue<DomainNameAttribute, string>((DomainNameAttribute dna) => dna.Name);</code>

The above is the detailed content of How Can I Dynamically Retrieve Attribute Values from a Class at Runtime?. 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