C#屬性編程

來源:互聯網
上載者:User

Attribute首先是一個類,在C#中, Attribute是作為編譯器指令來處理的
在.NET中,屬性的作用非常重要,無論是寫WEB控制項或是WEB服務,屬性的作用幾乎不可或缺,而序列化.程式安裝特徵等更離不開屬性,看上去很神秘,其實寫一個屬於自己的屬性也不難,在CodeProject和C#Corner上都有類似的示範代碼.這下面只是普通屬性,如果是AOP,則需要從ContextAttribute中繼承,關於AOP以及ContextAttribute,以後的文章將會專門講述,Code Project上也有相關的例子
using System;

namespace Test
{
 // Only allow this attribute to be added to classes
 [AttributeUsage(AttributeTargets.Class)]
 public class TestAttribute : Attribute
 {
  // A number with some imaginary importance
  public int TheNumber;

  // A string that could be useful somewhere
  public string Name;

  // The only constructor requiring that
  // TheNumber be set
  public TestAttribute(int TheNumber)
  {
   this.TheNumber = TheNumber;
   Name = "None";
  }

  // Method to illustrate that an attribute is really just
  // a class at heart.  This will be used in Driver.cs
  public void PrintOut()
  {
   Console.WriteLine("/tTheNumber = {0}", TheNumber);
   Console.WriteLine("/tName = /"{0}/"", Name);
  }
 }
}
上面就是一個屬性類了,很簡單的,注意的是,屬性類前面必須加上AttributeUsage屬性描述,裡面的AttributeTargets定義了該屬性的應用範圍,比如只應用於方法還是類還是全部適用,在上面這段代碼中,設定該屬性只能被類使用
你就可以在自己的類中用上自己的屬性了,比如
[Test(4, Name = "TestClassB")]
public class TestMyAtt
{}
仔細看,首先在TestAttribute 類的構造方法中,需要初始化TheNumber屬性,所以,在用TestAttribute的時候,必須有整數值,而Name 根據實際情況則可有可無了
實現自己的屬性其實還是很有用處的,個人認為對實現AOP模式是大有裨益的.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.