博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# 获取属性的description总结
阅读量:4557 次
发布时间:2019-06-08

本文共 1165 字,大约阅读时间需要 3 分钟。

现有一个结构体
public struct Desc { private byte val1; [Description("一个属性")] public byte des { get { return val1; } set { val1 = value; } } ///...以下省略 }获取Description代码:string str = ""; Desc desc = new Desc(); 不用反射 获取属性的特性 PropertyDescriptor pd = TypeDescriptor.GetProperties(typeof(Desc))["des"]; DescriptionAttribute description = pd == null ? null : pd.Attributes[typeof(DescriptionAttribute)] as DescriptionAttribute; str = description == null ? "" : description.Description; 用反射 获取属性的特性 PropertyInfo pi = typeof(Desc).GetProperty("des"); foreach (object obj in pi.GetCustomAttributes(false)) { if (obj is DescriptionAttribute) str=(obj as DescriptionAttribute).Description; } 不用反射 获取结构体的特性 AttributeCollection attributes = TypeDescriptor.GetAttributes(desc);//or typeof(Desc) DescriptionAttribute da = (DescriptionAttribute)attributes[typeof(DescriptionAttribute)]; if(attributes.Contains(da)) str = da.Description; 用反射 获取结构体的特性 Type myType = typeof(Desc); foreach (object obj in myType.GetCustomAttributes(false)) { if (obj is DescriptionAttribute) str = (obj as DescriptionAttribute).Description; }

转载于:https://www.cnblogs.com/wmlunge/archive/2011/10/09/2299263.html

你可能感兴趣的文章
Objective-C语言-内存管理
查看>>
迅雷API:实现文件下载
查看>>
Socket编程实践(2) Socket API 与 简单例程
查看>>
print 与标准输出
查看>>
pytest单元测试框架(day01)
查看>>
利用Azure Automation实现云端自动化运维(2)
查看>>
Linux学习说明
查看>>
【网络流24题】负载平衡问题(费用流)
查看>>
bzoj 3507 DP+哈希
查看>>
递归问题==优化 还有数据库sqlreader
查看>>
IOS第四天(2:字典转模型plist)
查看>>
什么是数据集
查看>>
Android开发数据库三层应用-DataSnap
查看>>
关于setTimeout运行机制
查看>>
2019 Multi-University Training Contest 4
查看>>
学号 《信息安全系统设计基础》第7周学习总结(一)
查看>>
POJ1741Tree [点分治]【学习笔记】
查看>>
BZOJ 3238: [Ahoi2013]差异 [后缀自动机]
查看>>
memcache 启动 failed to start
查看>>
欧拉函数与欧拉定理
查看>>