我们知道System.ComponentModel命名空间下有个名为DescriptionAttribute的类用于指定属性或事件的说明,我所调用的枚举值描述信息就是DescriptionAttribute类的Description属性值。
首先定义一个枚举
)]
cnblogs,
other
}
cnblogs,
other
}
默认情况下我们采用ArticleTypeList.csdn.ToString()的方式只能得到“csdn”,而不是“中国软件开发网络”,为了获取“中国软件开发网络”,我定义了下面这样一个静态方法:
}
直接通过GetEnumDescription(ArticleTypeList.csdn)便可获取到“中国软件开发网络”了,对于那些没有定义
DescriptionAttribute的子项则直接返回枚举值,例如
GetEnumDescription(ArticleTypeList.msdn)将返回“msdn”。
思路扩展
虽然使用DescriptionAttribute类基本上也满足了一般需求,可也不排除个别情况下需要多个描述值,针对这种情况,我们可以自System.Attribute类继承编写自定义属性类,例如:
}
然后调整一下ArticleTypeList的代码:
)]
cnblogs,
other
}
cnblogs,
other
}
最后编写调用的静态方法:
这样一来,对于DescriptionAttribute类描述信息,调用方法不变,而selfAttribute相关值的调用如下所示:
string text, test;
GetselfAttributeInfo(ArticleTypeList.csdn, out text, out test);