010. 使用.net架構提供的屬性

來源:互聯網
上載者:User

標籤:架構   ted   new   自訂屬性   基礎   頁面   write   中繼資料   private   

C#允許在類和類成員上聲明特性(類), 可在運行時解釋類和類的成員. 這個特性也稱為屬性, 使用Attribute.下面示範如何使用.net架構提供的屬性. 

 1 using System;  2 using System.Reflection; 3 public partial class _Default : System.Web.UI.Page  4 { 5     //自訂屬性類 6     [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] 7     public class BookAttribute : Attribute //Attribute 自訂屬性的基類 8     { 9         private string BookName;10         public BookAttribute(string BookName)11         {12             this.BookName = BookName;13         }14         public string Book15         {16             get17             {18                 return BookName;19             }20         }21     }22 23     //多次使用屬性類24     [Book("Asp.net入門基礎;")]25     [Book("C#實戰案例")]26     public class BookInfo27     {28         public string binfo = "圖書資訊***********";29         public BookInfo()30         {31 32         }33     }34 35     //頁面的page_load調用自訂的屬性樣本36     protected void Page_Load(object sender, EventArgs e)37     {38         //執行個體化BookInfo類39         BookInfo bf = new BookInfo();40         //對象數組41         object[] Bookattr;42         //擷取物件類型, 擷取有關成員特性的資訊並提供對成員中繼資料的訪問43         MemberInfo Typeinfo = typeof(BookInfo);44         //提取類型是屬性類的成員45         Bookattr = Typeinfo.GetCustomAttributes(typeof(BookAttribute), false);46         if (Bookattr.GetLength(0) != 0)47         {48             BookAttribute ba = (BookAttribute)(Bookattr[0]);//擷取屬性類的第一個成員49             BookAttribute ba2 = (BookAttribute)(Bookattr[1]);//擷取屬性類的第二個成員50             Response.Write(bf.binfo);51             Response.Write("<br/>");52             Response.Write("圖書名稱:" + ba.Book + ba2.Book);53         }   54     }55 }

 

010. 使用.net架構提供的屬性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.