C# 获取属性的description总结
2011-10-09 16:58
309 查看
现有一个结构体
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; }
相关文章推荐
- C#获取实体类属性名和值和DESCRIPTION值 | 遍历类对象
- C# 获取枚举 Enum 变量值的 Description 属性
- C# 获取枚举 Enum 变量值的 Description 属性
- C#获取实体类属性名和值和DESCRIPTION值 | 遍历类对象
- C# 获取枚举 Enum 变量值的 Description 属性
- C# 获取属性字段上DescriptionAttribute的值
- C#获取实体类属性名和值和DESCRIPTION值 | 遍历类对象
- 用C#获取CPU编号、硬盘编号等系统有关环境、属性
- c# 中webBrowser获取一个没有id和name属性的input标签的click事件
- C# 反射无法获取get set中属性
- C#用正则表达式 获取网页源代码标签的属性或值
- js获取屏幕高度,宽度,滚动距离属性总结
- 总结C#获取当前路径的7种方法
- 在C# ASP.NET中,要添加属性到控件中 在HTML页面获取控件中自己定义属性和值
- C#获取实体类属性名和值 | 遍历类对象
- C#获取属性
- 【.Net码农】C#获取实体类属性名和值 | 遍历类对象
- C#获取客户端相关信息实例总结
- c# WinForm开发 DataGridView控件的各种操作总结(单元格操作,属性设置)
- C#获得反射类属性;获取时间段内,选中的星期(可以多个)匹配的天数