??1.所有自定義屬性都必須繼承System.Attribute?
? ?2.自定義屬性的類名稱必須為 XXXXAttribute 即是已Attribute結尾
?
自定義屬性QuickWebApi
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]public class QuickWebApiAttribute: Attribute{public QuickWebApiAttribute(string _serviceCode,string _controllerName,string _actionName){ServicesCode = _serviceCode;ControllerName = _controllerName;ActionName = _actionName;}public string ServicesCode{ get; set; }public string ControllerName { get; set; }public string ActionName { get; set; }}
接口類
public interface ISchool{[QuickWebApi("SchoolServices", "School", "GetSchoolAll")]List<School> GetSchoolAll();[QuickWebApi("SchoolServices", "School", "GetSchoolListById")]List<School> GetSchoolListById(string schoolId);}
具體實現
static void Main(string[] args){Type t = typeof(ISchool);//獲取方法特性中ActionName為GetSchoolAll的特性var b = t.GetMethods().Single(p => CustomAttributeExtensions.GetCustomAttribute<QuickWebApiAttribute>(p).ActionName == "GetSchoolAll");QuickWebApiAttribute qu= CustomAttributeExtensions.GetCustomAttribute<QuickWebApiAttribute>(b);//循環遍歷foreach (MemberInfo p in t.GetMethods()){object[] Attribute1 = p.GetCustomAttributes(true);object[] Attribute2 = p.GetCustomAttributes(typeof(QuickWebApiAttribute), false);//獲取遍歷結果//QuickWebApiAttribute att = CustomAttributeExtensions.GetCustomAttribute<QuickWebApiAttribute>(p);string a = "";}Console.ReadKey();}
知識擴展
1 public enum AttributeTargets 2 { 3 // 摘要: 4 // 可以對程序集應用特性。 5 Assembly = 1, 6 // 7 // 摘要: 8 // 可以對模塊應用特性。 9 Module = 2, 10 // 11 // 摘要: 12 // 可以對類應用特性。 13 Class = 4, 14 // 15 // 摘要: 16 // 可以對結構應用特性,即值類型。 17 Struct = 8, 18 // 19 // 摘要: 20 // 可以對枚舉應用特性。 21 Enum = 16, 22 // 23 // 摘要: 24 // 可以對構造函數應用特性。 25 Constructor = 32, 26 // 27 // 摘要: 28 // 可以對方法應用特性。 29 Method = 64, 30 // 31 // 摘要: 32 // 可以對屬性應用特性。 33 Property = 128, 34 // 35 // 摘要: 36 // 可以對字段應用特性。 37 Field = 256, 38 // 39 // 摘要: 40 // 可以對事件應用特性。 41 Event = 512, 42 // 43 // 摘要: 44 // 可以對接口應用特性。 45 Interface = 1024, 46 // 47 // 摘要: 48 // 可以對參數應用特性。 49 Parameter = 2048, 50 // 51 // 摘要: 52 // 可以對委托應用特性。 53 Delegate = 4096, 54 // 55 // 摘要: 56 // 可以對返回值應用特性。 57 ReturnValue = 8192, 58 // 59 // 摘要: 60 // 可以對泛型參數應用特性。 61 GenericParameter = 16384, 62 // 63 // 摘要: 64 // 可以對任何應用程序元素應用特性。 65 All = 32767, 66 }
?