C#通过反射获取类自定义特性描述列表

C#通过反射获取类自定义特性描述列表

ID:40740492

大小:59.50 KB

页数:4页

时间:2019-08-07

C#通过反射获取类自定义特性描述列表_第1页
C#通过反射获取类自定义特性描述列表_第2页
C#通过反射获取类自定义特性描述列表_第3页
C#通过反射获取类自定义特性描述列表_第4页
资源描述:

《C#通过反射获取类自定义特性描述列表》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库

1、C#通过反射获取类自定义特性描述列表OO真的是个有趣的东西,我们都知道,创建类的时候,我们可以声明属性(property)、字段(field)等,而特性(Attribute)为人注意。在.NET中,特性使用,可分为.NET自带特性(如Description)和自定义特性。由于需求需要,本人粗浅研究了一下自定义特性的使用,下面就返回类的自定义特性描述列表进行梳理。自定义特性类:publicclassImportHeaderAttribute:System.Attribute { publicstringImportHeader{get;set;} publicintInd

2、ex{get;set;} publicImportHeaderAttribute(stringheader,intindex) { ImportHeader=header; Index=index; } }获取类自定义特性描述列表方法:///

///获取类自定义特性描述列表 /// ///目标类 ///自定义特性类 ///自定义特性 ///

3、ame="index">排序特性(升序),默认null不排序 ///返回类自定义特性描述列表,Key:属性(字段),value:特性描述 publicstaticIList>GetDescriptionList(stringcusName,stringindex=null) { try { List>classList=newList>();

4、List>indexList=newList>(); stringkey=string.Empty; stringvalue=string.Empty; #region循环目标类属性 foreach(PropertyInfoprointypeof(T).GetProperties())//循环目标类属性{ varattridures=pro.GetCustomAttributes(typeof(A),true);//自定义特性集合 key=pro.Name;

5、 Aa=default(A); foreach(objectattinattridures) { a=(A)att;//转换为自定义特性类对象 varaInfo=a.GetType().GetProperty(cusName);//获取对应特性的属性对象 if(aInfo!=null) { value=aInfo.GetValue(a).ToString(); classList.Add(newKeyValuePair(key,value));//赋值} if(!string.IsNullOrEmpty(index)) { varaIn

6、fo2=a.GetType().GetProperty(index); if(aInfo2!=null) { value=aInfo2.GetValue(a).ToString(); indexList.Add(newKeyValuePair(key,value)); } } } } #endregion #region循环目标类字段 foreach(FieldInfoFieldintypeof(T).GetFields()) { varattridures=Field.GetCustomAttributes(typeof(A),true

7、);//自定义特性集合 key=Field.Name; Aa=default(A); foreach(objectattinattridures) { a=(A)att;//转换为自定义特性类对象 varaInfo=a.GetType().GetProperty(cusName);//获取对应特性的属性对象 if(aInfo!=null) { value=aInfo.GetValue(a).ToString(); classList.Add(newKeyValuePair(key,value

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。