在一個(gè)類上面放一個(gè)標(biāo)簽,可以用來表示一些特定規(guī)則,比如某個(gè)對象的某個(gè)屬性不想被json化,那么我們在它頭上放個(gè)標(biāo)簽就行了,或是做ORM時(shí)指定某個(gè)Class對應(yīng)的table名字等。
最后標(biāo)簽是通過反射來調(diào)用的,一個(gè)類只要繼承了微軟的Attribute類就可以當(dāng)標(biāo)簽來使用了.
[AttributeUsage(AttributeTargets.All)]//指定Attribute的使用范圍,比如只能在class級別使用public class Column : Attribute{ public Column(string str) { this.str = str; } public string str { get; set; }}//第2個(gè)[AttributeUsage(AttributeTargets.All)]public class Table : Attribute{ public string someData { get; set; } //公開屬性還可以直接在標(biāo)簽上面寫入 public Table(string str) { this.str = str; } public string str { get; set; }}//2個(gè)屬性[Column("class")][Table("table class", someData = "ggc" )] //someData="ggc"是直接對attribute對象寫入值! public class Abc{ public string x { get; set; } [Column("attr")] public Int32 y { get; set; }}PRotected void Page_Load(object sender, EventArgs e){ //通過反射可以調(diào)用到這個(gè)類型頭上的attr Type type = typeof(Abc); bool isGot = Attribute.IsDefined(type, typeof(Column)); //查看有沒有某個(gè)Attribute Attribute[] attrs = Attribute.GetCustomAttributes(type); //批量獲取 string xy = attrs.First().GetType().Name; //可以查看它的名字來選擇想要的,或是看有沒有想要的. Column column = (Column)Attribute.GetCustomAttribute(type, typeof(Column)); //強(qiáng)轉(zhuǎn) Column[] columns = (Column[])Attribute.GetCustomAttributes(type, typeof(Column)); column = columns[0]; string x = column.str; //調(diào)用方法或是公開屬性等等都可以 //實(shí)例化之后也是可以一樣拿 Abc a = new Abc(); PropertyInfo info = a.GetType().GetProperty("y"); Column attribute2 = (Column)Attribute.GetCustomAttribute(info, typeof(Column)); string xyz = attribute2.str;}新聞熱點(diǎn)
疑難解答
圖片精選