如何用字符串值定义枚举? [英] How to define an enum with string value?

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

问题描述

我正在尝试定义一个 Enum 并添加在 CSV 或类似文件中使用的有效通用分隔符.然后我将把它绑定到一个 ComboBox 作为数据源,所以每当我添加或删除 Enum 定义时,我不需要更改组合框中的任何内容.

I am trying to define an Enum and add valid common separators which used in CSV or similar files. Then I am going to bind it to a ComboBox as a data source so whenever I add or remove from the Enum definition, I would not need to change anything in the combo box.

问题是如何用字符串表示定义枚举,例如:

The problem is how can I define enum with string representation, something like:

public enum SeparatorChars{Comma = ",", Tab = " ", Space = " "}

推荐答案

你不能 - 枚举值必须是整数值.您可以使用属性将字符串值与每个枚举值相关联,或者在这种情况下,如果每个分隔符都是单个字符,您可以只使用 char 值:

You can't - enum values have to be integral values. You can either use attributes to associate a string value with each enum value, or in this case if every separator is a single character you could just use the char value:

enum Separator
{
    Comma = ',',
    Tab = '	',
    Space = ' '
}

(只是为了澄清,您不能使 char 成为枚举的基础类型,但您可以使用 char 常量来分配对应的整数值每个枚举值.上面枚举的基础类型是int.)

( Just to clarify, you can't make char the underlying type of the enum, but you can use char constants to assign the integral value corresponding to each enum value. The underlying type of the above enum is int.)

如果你需要一个扩展方法:

Then an extension method if you need one:

public string ToSeparatorString(this Separator separator)
{
    // TODO: validation
    return ((char) separator).ToString();
}

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

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