c# 属性(Attribute)

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的特征让我很困惑,编译器做了什么手脚,规则是啥

posted @ 2010-05-21 22:26  Delon  阅读(1271)  评论(0编辑  收藏  举报