c# 屬性(Attribute)

來源:互聯網
上載者:User

C# 屬性特徵非常有用,以下是屬性特徵的實驗性總結(c#2.0)

1.屬性只在被訪問時構造,每訪問一次就構造一次。

 

class MyAttribute : Attribute 
{
public MyAttribute(string name)
{
this.name = name;
COUNT++;
}

internal string name = string.Empty;
internal static int COUNT = 0;
}

[MyAttribute("attribute")]
class MyClass
{
public MyClass()
{

}
}

class Program
{
static void Main(string[] args)
{
MyClass myClass = new MyClass();


myClass.GetType().GetCustomAttributes(false);
myClass.GetType().GetCustomAttributes(false);
myClass.GetType().GetCustomAttributes(false);

//3
System.Console.WriteLine(MyAttribute0.COUNT);
}
}

 

 

 

2.應用某一層級上的屬性集合,編譯後的順序可能會改變(具體規則未知)。

 

    [MyAttribute("myattribute0"), MyAttribute("myattribute1"), MyAttribute("myattribute2")]
[MyAttribute("myattribute11")]
[MyAttribute("myattribute22")]
class MyClass
{
public MyClass()
{

}
}

class Program
{
static void Main(string[] args)
{
MyClass myClass = new MyClass();
object[] objs = myClass.GetType().GetCustomAttributes(typeof(MyAttribute),true);
foreach(MyAttribute myAttribute in objs)
{
Console.WriteLine(myAttribute.name);
}

//myattribute0
//myattribute22
//myattribute1
//myattribute2
//myattribute11
}
}

 

 

 

 

3.屬性的可附帶資料只限於單一資料型別

 

bool,byte,char,double,float,int,long,short,string,System.Type,object,enum以上類型的array

 

4.屬性常用API(可參考MSND)

 

AttributeUsage //屬性特徵類
Attribute.GetCustomAttribute
Attribute.GetCustomAttributes
Type.GetCustomAttribute
Type.GetCustomAttributes
......

 

5.疑問

  @屬性竟然是中繼資料層級的,上面1條目的特徵是否太浪費了

  @條目2的特徵讓我很困惑,編譯器做了什麼手腳,規則是啥

相關文章

聯繫我們

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