枚举值字典作为字符串

时间:2012-03-08 13:52:30

标签: c# .net string dictionary enums

我正在尝试创建一个API,该API中的一个函数将Enum作为参数,然后对应于使用的字符串。

public enum PackageUnitOfMeasurement
{
        LBS,
        KGS,
};

对此进行编码的简单方法必须列出代码中的每个案例。但是因为它们是30个案例,所以我试图避免这种情况并使用Dictionary Data Structure,但我似乎无法将这些点与如何将值与枚举联系起来。

if(unit == PackageUnitOfMeasurement.LBS)
       uom.Code = "02";  //Please note this value has to be string
else if (unit == PackageUnitOfMeasurement.KGS)
       uom.Code = "03";

5 个答案:

答案 0 :(得分:9)

以下是将映射存储在字典中并稍后检索值的一种方法:

var myDict = new Dictionary<PackageUnitOfMeasurement,string>();
myDict.Add(PackageUnitOfMeasurement.LBS, "02");
...

string code = myDict[PackageUnitOfMeasurement.LBS];

另一种选择是使用DecriptionAttribute之类的东西来装饰每个枚举项,并使用反射来读出这些内容,如Getting attributes of Enum's value中所述:

public enum PackageUnitOfMeasurement
{
        [Description("02")]
        LBS,
        [Description("03")]
        KGS,
};


var type = typeof(PackageUnitOfMeasurement);
var memInfo = type.GetMember(PackageUnitOfMeasurement.LBS.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),
    false);
var description = ((DescriptionAttribute)attributes[0]).Description;

第二种方法的好处是你可以保持映射接近枚举,如果有任何变化,你不需要寻找你需要更新的任何其他地方。

答案 1 :(得分:4)

您可以指定枚举元素的数字值

public enum PackageUnitOfMeasurement {
    None = 0,
    LBS = 2,
    KGS = 3,
    TONS = 0x2a
};

然后您可以使用

简单地转换单位
uom.Code = ((int)unit).ToString("X2");

注:

根本问题是,对单位进行硬编码是否是一个好主意。通常,这类内容应放入数据库的查找表中,以便随时添加新单元,而无需更改程序代码。


更新:

我添加了一个包含HEX代码的示例。格式“X2”产生两位十六进制值。以十六进制表示法输入大于9的所有数字,例如c#中的0xA == 100x10 == 16

答案 2 :(得分:2)

我会使用附加到枚举的属性。像这样:

var type = typeof(PackageUnitOfMeasurement);
var memInfo = type.GetMember(PackageUnitOfMeasurement.LBS.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute),
    false);
var description = ((DescriptionAttribute)attributes[0]).Description;

这取自这个问题,Getting attributes of Enum's value。其中特别要求返回枚举属性。

答案 3 :(得分:1)

Oded的解决方案很好,但我过去使用的替代方法是使用附加到包含相应字符串的枚举值的属性。

这就是我的所作所为。

public class DisplayStringAttribute : Attribute
{
    private readonly string value;
    public string Value
    {
        get { return value; }
    }

    public DisplayStringAttribute(string val)
    {
        value = val;
    }
}

然后我可以这样定义我的枚举:

public enum MyState 
{ 
    [DisplayString("Ready")]
    Ready, 
    [DisplayString("Not Ready")]
    NotReady, 
    [DisplayString("Error")]
    Error 
};

而且,为了我的目的,我创建了一个转换器,所以我可以绑定到枚举:

public class EnumDisplayNameConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        Type t = value.GetType();
        if (t.IsEnum)
        {
            FieldInfo fi = t.GetField(value.ToString());
            DisplayStringAttribute[] attrbs = (DisplayStringAttribute[])fi.GetCustomAttributes(typeof(DisplayStringAttribute),
                false);
            return ((attrbs.Length > 0) && (!String.IsNullOrEmpty(attrbs[0].Value))) ? attrbs[0].Value : value.ToString();
        }
        else
        {
            throw new NotImplementedException("Converter is for enum types only");
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Oded的解决方案可能表现得更快,但这个解决方案具有很大的灵活性。如果你真的想要,你可以添加一大堆属性。但是,如果你这样做,你可能最好不要创建一个类而不是使用枚举!

答案 4 :(得分:0)

默认值PackageUnitOfMeasurement.LBS 0 同样PackageUnitOfMeasurement.KBS 1

因此PackageUnitOfMeasurement的集合实际上是一个包含整数值的集合(即int)。

你的问题并不完全清楚......

一个字典集合有一个Key和一个Value听起来你想要使用PackageUnitOfMeasurement有一个Key,这对于将值转换为整数来说是微不足道的。

PackageUnitOfMeasurement example = PackageUnitOfMeasurement.LBS
int result = (int)example;
var myDict = new Dictionary<PackageUnitOfMeasurement,string>(); 
myDict.Add(result,"some value here"
相关问题