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

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

问题描述

我试图定义一个 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枚举SeparatorChars {Comma =,,Tab = \t,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 = '\t',
    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天全站免登陆