将字符串值添加到枚举 [英] add string value to enum

查看:108
本文介绍了将字符串值添加到枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部问候,



我有这个Enum类型,我想给标准和值一个字符串值,我该怎么办?



 public enum ItemsChoiceType1 {

/// < ; 备注/ >
条件,

/// < 备注/ >
价值,
}





我想在字符串上传送ItemsChoiceType1而不添加任何内容枚举类型,因为它是由我使用的API提供的

请帮助!

解决方案

您可以添加Description属性



  public   enum  ChartType : short  
{
Pie = 1
Donut = < span class =code-digit> 2 ,
Column = 3 ,
[描述( 列堆积的 )]
ColumnStacked = 4
Area = 5
[描述( 堆积区域)]
AreaStacked = 6
[描述( Area Spline)]
AreaSpline = 7
Bar = 8
[描述( Bar Stacked)]
BarStacked = 9
行= 10
Spline = 11
}



您可以通过以下h获得描述elper

 public static class EnumExt 
{
public static string Description(this Enum en)
{
string result = en的ToString();
类型EnumType = en.GetType();

FieldInfo fi = EnumType.GetField(result);
var da = Attribute.GetCustomAttribute(fi,typeof(DescriptionAttribute))as DescriptionAttribute;
return(da!= null?da.Description:result);
}
}





 ChartType.BarStacked.Description()


Greeting All ,

I have this Enum type and I want to give a string value to criteria and value , how should I do ?

public enum ItemsChoiceType1 {

    /// <remarks/>
    Criteria,

    /// <remarks/>
    Value,
}



I would like to convet ItemsChoiceType1 on string without adding any things to the enum type because it is provided by the API that I use
Please Help !

解决方案

You can add Description attribute

public enum ChartType : short
    {
        Pie = 1,
        Doughnut = 2,
        Column = 3,
        [Description("Column Stacked")]
        ColumnStacked = 4,
        Area = 5,
        [Description("Area Stacked")]
        AreaStacked = 6,
        [Description("Area Spline")]
        AreaSpline = 7,
        Bar = 8,
        [Description("Bar Stacked")]
        BarStacked = 9,
        Line = 10,
        Spline = 11
    }


You can get Description by below helper

public static class EnumExt
    {
        public static string Description(this Enum en)
        {
            string result = en.ToString();
            Type EnumType = en.GetType();

            FieldInfo fi = EnumType.GetField(result);
            var da = Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute)) as DescriptionAttribute;
            return (da != null ? da.Description : result);
        }
    }



ChartType.BarStacked.Description()


这篇关于将字符串值添加到枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆