」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在運行時從類中動態檢索屬性值?

如何在運行時從類中動態檢索屬性值?

發佈於2025-02-07
瀏覽:772

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

運行時檢索屬性

本文介紹一種通用的方法,用於動態訪問和提取類的屬性值。

使用專用方法

定義一個接受類型參數的通用方法:

public string GetDomainName()

方法內部:

  • 使用 typeof(T).GetCustomAttributes 檢索自定義屬性:

      var dnAttribute = typeof(T).GetCustomAttributes(
        typeof(DomainNameAttribute), true
      ).FirstOrDefault() as DomainNameAttribute;
  • 如果屬性存在,則返回其值:

      if (dnAttribute != null)
      {
        return dnAttribute.Name;
      }
  • 否則,返回 null:

      return null;

實用程序擴展方法

為了更廣泛的適用性,將該方法泛化以處理任何屬性:

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

擴展方法內部:

  • 檢索自定義屬性:

      var att = type.GetCustomAttributes(
        typeof(TAttribute), true
      ).FirstOrDefault() as TAttribute;
  • 如果屬性存在,則使用提供的 valueSelector 來提取所需的值:

      if (att != null)
      {
        return valueSelector(att);
      }
  • 否則,返回該類型的默認值:

      return default(TValue);

使用示例

  • 檢索 MyClassDomainName 屬性:
string name = typeof(MyClass).GetDomainName();
  • 使用擴展方法檢索 MyClass 的任何屬性值:
string name = typeof(MyClass)
    .GetAttributeValue((DomainNameAttribute dna) => dna.Name);
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3