摘要:本文主要向大家介绍了C#编程之C# 给枚举定义DescriptionAttribute,把枚举转换为键值对,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。
本文主要向大家介绍了C#编程之C# 给枚举定义DescriptionAttribute,把枚举转换为键值对,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。
在C#中,枚举用来定状态值很方便,例如我定义一个叫做Season的枚举
public enum Season
{
Spring = 1,
Summer = 2,
Autumn = 3,
Winter = 4
}
枚举名是不能出现空格,()-/等字符
我们想把Spring显示为春天,我们要自己定义说明信息,我们可以使用DescriptionAttribute,如下
public enum Season
{
[Description("春 天")]
Spring = 1,
[Description("夏 天")]
Summer = 2,
//[Description("秋 天")]
Autumn = 3,
[Description("冬 天")]
Winter = 4
}
下面我们来写个扩展方法,来得到枚举的说明信息,如下
///
///
枚举值
///
当枚举值没有定义DescriptionAttribute,是否使用枚举名代替,默认是使用
///
public static string GetDescription(this Enum value, Boolean nameInstead = true)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name == null)
{
return null;
}
FieldInfo field = type.GetField(name);
DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attribute == null&&nameInstead == true)
{
return name;
}
return attribute == null ? null : attribute.Description;
}
把枚举转换为键值对集合
///
///
枚举类型
///
获得值得文本
///
public static Dictionary
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C#.NET频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号