日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > C# >内容正文

C#

C# 通过反射获取方法/类上的自定义特性

發(fā)布時間:2023/12/13 C# 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C# 通过反射获取方法/类上的自定义特性 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

??1.所有自定義屬性都必須繼承System.Attribute?

? ?2.自定義屬性的類名稱必須為 XXXXAttribute 即是已Attribute結(jié)尾

?

自定義屬性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);}

具體實現(xiàn)

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);//循環(huán)遍歷foreach (MemberInfo p in t.GetMethods()){object[] Attribute1 = p.GetCustomAttributes(true);object[] Attribute2 = p.GetCustomAttributes(typeof(QuickWebApiAttribute), false);//獲取遍歷結(jié)果//QuickWebApiAttribute att = CustomAttributeExtensions.GetCustomAttribute<QuickWebApiAttribute>(p);string a = "";}Console.ReadKey();}

知識擴展

1 public enum AttributeTargets 2 { 3 // 摘要: 4 // 可以對程序集應(yīng)用特性。 5 Assembly = 1, 6 // 7 // 摘要: 8 // 可以對模塊應(yīng)用特性。 9 Module = 2, 10 // 11 // 摘要: 12 // 可以對類應(yīng)用特性。 13 Class = 4, 14 // 15 // 摘要: 16 // 可以對結(jié)構(gòu)應(yīng)用特性,即值類型。 17 Struct = 8, 18 // 19 // 摘要: 20 // 可以對枚舉應(yīng)用特性。 21 Enum = 16, 22 // 23 // 摘要: 24 // 可以對構(gòu)造函數(shù)應(yīng)用特性。 25 Constructor = 32, 26 // 27 // 摘要: 28 // 可以對方法應(yīng)用特性。 29 Method = 64, 30 // 31 // 摘要: 32 // 可以對屬性應(yīng)用特性。 33 Property = 128, 34 // 35 // 摘要: 36 // 可以對字段應(yīng)用特性。 37 Field = 256, 38 // 39 // 摘要: 40 // 可以對事件應(yīng)用特性。 41 Event = 512, 42 // 43 // 摘要: 44 // 可以對接口應(yīng)用特性。 45 Interface = 1024, 46 // 47 // 摘要: 48 // 可以對參數(shù)應(yīng)用特性。 49 Parameter = 2048, 50 // 51 // 摘要: 52 // 可以對委托應(yīng)用特性。 53 Delegate = 4096, 54 // 55 // 摘要: 56 // 可以對返回值應(yīng)用特性。 57 ReturnValue = 8192, 58 // 59 // 摘要: 60 // 可以對泛型參數(shù)應(yīng)用特性。 61 GenericParameter = 16384, 62 // 63 // 摘要: 64 // 可以對任何應(yīng)用程序元素應(yīng)用特性。 65 All = 32767, 66 }

?

轉(zhuǎn)載于:https://www.cnblogs.com/happygx/p/9066714.html

總結(jié)

以上是生活随笔為你收集整理的C# 通过反射获取方法/类上的自定义特性的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。