Attribute基礎,園友不用看,浪費您時間
2012-02-01 19:09 海不是藍 閱讀(388) 評論(0) 收藏 舉報|
Attribute基礎 |
Attribute作用就是為程序添加說明信息,特性都是繼承System.Attribute。所有特性都必須是System.Attribute的派生類(別想逆天!)。
特性是個類,這個類很簡單,簡單到只有基本的字段或屬性,別想在特性里面添加方法,這個也是逆天的。
創建個簡單的特性
[AttributeUsage(AttributeTargets.All)]
public class TestAttribute : Attribute
{
private string str;
public string Str
{
get { return str; }
set { str = value; }
}
public TestAttribute(string str)
{ this.str = str; }
}
特性前有個AttributeUsage特性,它指明TextAttribute能夠應用的范圍,這里是所有類型的項。
使用這個特性
[TestAttribute("blah blah blah......")]
public class Test { }
獲取Test類上的特性
通常用下面2個方法獲取
1.Attribute.GetCustomAttribute
public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType);
2.MemberInfo類中的GetCustomAttributes方法
public abstract object[] GetCustomAttributes(bool inherit);
參數如果為true,那么所有基類的特性都會被包含進來,否則獲取指定類型本身定義的特性。
class Program
{
static void Main()
{
Type t = typeof(Test);
Type t1 = typeof(TestAttribute);
TestAttribute ta = (TestAttribute)Attribute.GetCustomAttribute(t, t1);
Console.WriteLine(ta.Str);
Console.WriteLine("---------------------------------------");
object[] obj = t.GetCustomAttributes(false);
foreach (object o in obj)
{
TestAttribute ta1 = (TestAttribute)o;
Console.WriteLine("{0}---{1}", o, ta1.Str);
}
Console.Read();
}
}

特性屬性的其它賦值方法
private string str1;
public string Str1
{
get { return str1; }
set { str1 = value; }
}
public TestAttribute(string str)
{
this.str = str;
this.str1 = "null";
}
這個時候多了個str1字段,但是構造函數沒有提供外面對他賦值的就會。
這個是的賦值方式就是下面的樣子
[TestAttribute("blah blah blah......", Str1 = "123")]
public class Test { }
《clr via c#》的Attribute那一章今天沒心情看了,有空看看
浙公網安備 33010602011771號