如何成功转换多值枚举?

时间:2019-06-10 11:26:40

标签: c# parsing enums casting tostring

问题: 我可以用enum返回单个值enum.ToString()的字符串表示形式。在多值enum的情况下(例如:使用OR运算符|表示),我在enum.ToString()调用中得到的都是整数值,因为{ {1}}无法enum

解决方法/障碍: 我无法在parse中创建多个具有相同值的实例,例如:

enum

因为这违反了标准,并且IDE对此感到非常皱眉。

问题示例:

public enum Languages: int
{
     English = 0, // From American English
     English = 1, // From UK English
     Spanish = 2, // From Castillian Spanish
     Spanish = 3, // From Latin American Spanish
     Portuguese = 4 // From Brasilian Portuguese
     Portuguese = 5, // From European Portuguese
}

期望(或我正在尝试做的事情):

我期望条件应该匹配,所以public enum Languages: int { English = 0 | 1, // American or UK Spanish = 2 | 3, // Castillian or Latin American Portuguese = 4 | 5, // Brasil or Portugal MyMadeUpLanguage = 6, } int selectedLanguage = 1; Languages result = (Languages)Enum.Parse(typeof(Languages), selectedLanguage); string resultString = result.ToString(); // This is where '1' is returned and not English. int nextSelectedLanguage = 6; Languages differentResult = (Languages)Enum.Parse(typeof(Languages), nextSelectedLanguage); string nextResultString = differentResult.ToString(); // This returns 'MyMadeUpLanguage', as we would expect. 0会匹配1,然后我的枚举结果将是English,因此,返回的字符串将是Languages.English,而不是English

相反,发生的 似乎是对1 parse的调用只是返回为enum而不是int类型(参考上面的示例),因此-当然-Language方法将返回enum.ToString()

对于多值int,如果从enum2的值足以满足x <= int.MaxValue的要求,我该如何致电{{1} } enum成功转换为预期的parse(因此,将在返回enum方法时带回正确的字符串)?

1 个答案:

答案 0 :(得分:1)

我建议使用Flags属性,例如:

[Flags]
public enum Languages: int
{
     None = 0,                      // None 

     English    = 1 << 30,          // Languages  
     Spanish    = 1 << 29,  
     Portuguese = 1 << 28,   
     MyMadeUpLanguage = 1 << 27, 

                                    // Dialects
     EnglishUS = English | 1,       // From American English
     EnglishGB = English | 2,       // From UK English
     EnglishCA = English | 3,       // From Canada English
     SpanishES = Spanish | 1,       // From Castillian Spanish
     SpanishLA = Spanish | 2,       // From Latin American Spanish
     PortugueseBR = Portuguese | 1, // From Brasilian Portuguese
     PortuguesePT = Portuguese | 2, // From European Portuguese 

     MyMadeUpLanguageDialect1 = MyMadeUpLanguage | 1
}

典型比较:

Languages selectedLanguage ...

if (Languages.EnglishGB & Languages ==  Languages.EnglishGB) {
  // From Exactly English Great Britain
  ...
}

if (Languages.English & Languages == Languages.English) {
  // From some kind of English (Great Britain, or US dialect)
  ...
}