溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C#反射訪問屬性規(guī)范有哪些

發(fā)布時(shí)間:2021-06-24 14:28:43 來源:億速云 閱讀:136 作者:Leah 欄目:編程語言

本篇文章給大家分享的是有關(guān)C#反射訪問屬性規(guī)范有哪些,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

C#反射——屬性規(guī)范

C#

[Author("H. Ackerman", version = 1.1)]  class SampleClass

在概念上等效于:

C#

Author anonymousAuthorObject = new Author("H. Ackerman");  anonymousAuthorObject.version = 1.1;

但是,直到查詢 SampleClass 以獲取屬性時(shí)才會(huì)執(zhí)行此代碼。對(duì) SampleClass 調(diào)用 GetCustomAttributes 會(huì)導(dǎo)致按上述方式構(gòu)造并初始化一個(gè) Author 對(duì)象。如果類還有其他屬性,則其他屬性對(duì)象的以類似方式構(gòu)造。然后 GetCustomAttributes 返回 Author 對(duì)象和數(shù)組中的任何其他屬性對(duì)象。之后就可以對(duì)此數(shù)組進(jìn)行迭代,確定根據(jù)每個(gè)數(shù)組元素的類型所應(yīng)用的屬性,并從屬性對(duì)象中提取信息。

C#反射——示例

下面是一個(gè)完整的示例。定義一個(gè)自定義屬性,將其應(yīng)用于若干實(shí)體并通過反射進(jìn)行檢索。

C#

[System.AttributeUsage(System.AttributeTargets.Class |                         System.AttributeTargets.Struct,                         AllowMultiple = true)  // multiuse attribute  ]  public class Author : System.Attribute  {      string name;      public double version;       public Author(string name)      {          this.name = name;          version = 1.0;  // Default value      }       public string GetName()      {          return name;      }  }   [Author("H. Ackerman")]  private class FirstClass  {      // ...  }   // No Author attribute  private class SecondClass  {      // ...  }   [Author("H. Ackerman"), Author("M. Knott", version = 2.0)]  private class ThirdClass  {      // ...  }   class TestAuthorAttribute  {      static void Main()      {          PrintAuthorInfo(typeof(FirstClass));          PrintAuthorInfo(typeof(SecondClass));          PrintAuthorInfo(typeof(ThirdClass));      }       private static void PrintAuthorInfo(System.Type t)      {          System.Console.WriteLine("Author information for {0}", t);          System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  // reflection           foreach (System.Attribute attr in attrs)          {              if (attr is Author)              {                  Author a = (Author)attr;                  System.Console.WriteLine("   {0}, version {1:f}", a.GetName(), a.version);              }          }      }  }

輸出

Author information for FirstClass

H. Ackerman, version 1.00

Author information for SecondClass

Author information for ThirdClass

H. Ackerman, version 1.00

M. Knott, version 2.00

以上就是C#反射訪問屬性規(guī)范有哪些,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI