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的特徵讓我很困惑,編譯器做了什麼手腳,規則是啥