自定義Attribute:html
1)Attribute都從System. Attribute類繼承,類名通常以Attribute結尾web
2) 標記類的用途—AttributeUsage標記(標記的標記):AttributeTargets:能夠添加到哪些成員上。 AllowMultiple:是否容許在一個成員上標記這個Attribute的多個實例,默認false。標註在Attribute類的類名上方。ui
3)Attribute只是給類、成員作標記,自己沒有什麼意義,不會發生任何動做,就像小偷踩點在門上作標記(StealableAttribute)同樣,具體這個標記會起到什麼做用是由使用這個類、成員的代碼決定的。this
案例代碼:spa
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; namespace _11動態建立一個對象的html表單頁 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Person p1 = new Person(); p1.Name = "hzy"; p1.Age = 25; p1.Email = "hzy@sina.com"; // Car car = new Car() { Brand = "蘭博基尼", LicenseNo = "京00000" }; CreateFormByObject(p1); } private void CreateFormByObject(object obj) { Type type = obj.GetType();//獲取這個對象的type StringBuilder sbHtml = new StringBuilder(); PropertyInfo[] pinfo = type.GetProperties();//獲取當前對象中的全部的屬性 foreach (PropertyInfo item in pinfo) { //這句話的意思是,獲取當前遍歷的屬性Brand上所標記的UserLanguageAttribute特性 object[] objs = item.GetCustomAttributes(typeof(UserLanguageAttribute), false); //獲取全部標記的特性,不包含父類中繼承下來的特性 //item.GetCustomAttributes(false) //objs[0].GetType().Name //表示當前屬性標記了這個特性(UserLanguageAttribute) if (objs.Length > 0) { UserLanguageAttribute ula = (UserLanguageAttribute)objs[0]; sbHtml.Append(ula.DisplayLanguage + ":<input value=\"" + item.GetValue(obj, null) + "\"/><br/>"); } else { sbHtml.Append(item.Name + ":<input value=\"" + item.GetValue(obj, null) + "\"/><br/>"); } } webBrowser1.DocumentText = sbHtml.ToString(); } } public class Person { [UserLanguage("xing ming")] public string Name { get; set; } [UserLanguage("nian ling")] public int Age { get; set; } //[UserLanguage("yi mei er")] public string Email { get; set; } } public class Car { [UserLanguage("品牌")] public string Brand { get; set; } [UserLanguage("車牌號碼")] public string LicenseNo { get; set; } } public class UserLanguageAttribute : Attribute { public UserLanguageAttribute(string lan) { this.DisplayLanguage = lan; } public string DisplayLanguage { get; set; } } }
運行結果:code