请问如何获取属性的说明信息

比如我有一个枚举
public enum _SourceType
{
[Description("物料")]
Storage_Goods,
}

我要如何获取到"物料"这个说明信息呢?

如果这样不行,那么还有其它方法可以为枚举加说明信息吗?这个说明信息要在其它地方能够能过编程方式获取的到。
...全文
122 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
风之影子 2012-10-22
  • 打赏
  • 举报
回复
http://topic.csdn.net/u/20110614/23/8bc008eb-c7f0-46d2-8353-c82240f09290.html
assky124 2012-10-22
  • 打赏
  • 举报
回复
基本原来类似下面的代码


Type type = typeof(Button);
Object[] attrs = type.GetCustomAttributes(typeof(DescriptionAttribute), true);
if (attrs != null && attrs.Length > 0)
{

System.ComponentModel.DescriptionAttribute desAttr = attrs[0] as System.ComponentModel.DescriptionAttribute;
MessageBox.Show(desAttr.Description);
}
  • 打赏
  • 举报
回复
谢谢,这个我已经看过了。
  • 打赏
  • 举报
回复
这样不太好,我还得建立类成员与说明信息的对应信息,我是想直接获取成员的attribute信息。
风之影子 2012-10-22
  • 打赏
  • 举报
回复
你手工把你类内成员的说明信息用常量写入字符串数组,调用方法的时候直接返回就行。

  • 打赏
  • 举报
回复
要如何获取到类成员的相关说明信息呢?
风之影子 2012-10-22
  • 打赏
  • 举报
回复
写一个返回字符串数组或是返回list的方法,这个方法调用就返回类成员的相关说明信息。


风之影子 2012-10-22
  • 打赏
  • 举报
回复
foreach (PropertyInfo var in t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Static))
{
foreach (object item in var.GetCustomAttributes(false))
{
if (item is DescriptionAttribute)
{
MessageBox.Show(var.Name+"----"+(item as DescriptionAttribute).Description);
}
}
}



t是你的类
Hauk 2012-10-22
  • 打赏
  • 举报
回复

DescriptionAttribute[] das = typeof(_SourceType).GetField("Storage_Goods")
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.OfType<DescriptionAttribute>().ToArray();
if (das.Length > 0)
Console.WriteLine(das[0].Description);


或者:


Console.WriteLine(typeof(_SourceType).GetField("Storage_Goods")
.GetCustomAttributesData()[0].ConstructorArguments[0].Value);

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧