1 .描述
屬性提供功能強大的方法以將聲明資訊與 C# 代碼(類型、方法、屬性等)相關聯。屬性與程式實體關聯後,即可在運行時使用名為“反射”的技術查詢屬性。
屬性以兩種形式出現:
2. 範例程式碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NetTest
{
public class TestAttribute
{
public void Test()
{
PrintAuthorInfo(typeof(CustomAttribute));
}
/*
Obsolete 屬性將某個程式實體標記為一個建議不再使用的實體。每次使用被標記為已淘汰的實體時,
隨後將產生警告或錯誤,這取決於屬性是如何配置的,第二個參數是true時,編譯時間顯示錯誤
*/
[Obsolete("please use aonther method,this is obsolate",true)]
public void TestObsolate()
{
Console.Out.WriteLine("welcome");
}
private static void PrintAuthorInfo(System.Type t)
{
System.Console.WriteLine("Author information for {0}", t);
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t); // reflection
foreach (System.Attribute attr in attrs)
{
if (attr is Author)
{
Author a = (Author)attr;
System.Console.WriteLine(" {0}, version {1:f}", a.Name, a.version);
}
}
}
//應用自訂屬性
[Author("Jack",version=1.0)]
[Author("TJ",version=2.0)]
class CustomAttribute
{
public void Test()
{
Console.Out.WriteLine("Test custom attribute");
}
}
//自訂的屬性,整合屬性類
[System.AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct,AllowMultiple=true)]
class Author : System.Attribute
{
private string name;
public double version;
public Author(string name)
{
this.name = name;
version = 1.0;
}
public string Name
{
get { return this.name; }
}
}
}
}