.net 如何设置和检索特性信息(attribute)
生活随笔
收集整理的這篇文章主要介紹了
.net 如何设置和检索特性信息(attribute)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? 1.??????? 創建一個System.Attribute的子類
AllowMultipe?=?true,????//允許應用多次
Inherited?=?false????????//不繼承到派生類
)]
public?class?SampleAttribute?:?System.Attribute
{
????private?string?descr;
????private?string?author;
????private?string?title;
????public?string?Descr
{
????get?{return?descr;}
????set?{descr?=?value;}
}
public?string?Author
{
????get?{return?author?;}
????set?{author?=?value?;}
}
public?string?Title
{
????get?{return?title?;}
????set?{title?=?value?;}
}
//構造方法
Public?SampleAttribute?(string?description)
{
????descr?=?description;
}
}
在創建子類時,可以為該類標注上AttributeUsage特性. 同時指定新定義的自定義特性可以應用于哪些類型. 例如, 如果像下面這樣給一個屬性(property)添加剛建立的自定義特性, 編譯器就會拋出異常, 提示”SampleAttribute對本聲明類型無效,只對聲明類和方法有效”
public?string?SomeProerty
{
????get?{return?"ok"}
}
2.??????? 使用定義好的自定義特性
public?class?TestApp
{
public?void?Test?()
{
????????Console.WriteLine?("Author?{0},?Descr?{1}",?author,?descr);
}
}
?
Sample(…)是SampleAttribute(…)的省略寫法. 該代碼會命名編譯器調用自定義特性對象的構造函數, 并傳入字符串的值(“description for sample attribute”由構造函數初始化), 然后再將”Author”屬性設置為”Tester”(Author = “Tester”是由屬性賦值)來完成一個特性對象的創建. 當然還可以設置其他的屬性的值, 例如:
[Sample?(“description?for?sample?attribute”,?Author?=?“Tester”,?Title?=?“Title?for?this”,?Descr?=?“cover?with?old?descr”?)] ?
3.??????? 利用反射檢索特性信息
public?static?void?Main(string[]?args)
{
????????MemberInfo?info?=?typeof(TestApp);?//TestApp是Test()所在的類名
????????SampleAttribute?sample?=?(SampleAttribute)Attribute.GetCustomAttribute(info,?typeof(SampleAttribute));
????????if(sample?!=?null)
{
????Console.WriteLine("Author:?{0},?Descr:?{1}?",?sample.Author,?sample.Descr);????
????Console.ReadLine();
}
}
?完整代碼下載
轉載于:https://www.cnblogs.com/Niyowong/archive/2008/04/14/1152962.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的.net 如何设置和检索特性信息(attribute)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Vue 新手学习笔记:vue-eleme
- 下一篇: 初学tornado之MVC版hellow