【问题标题】:Cannot convert string to Enum type I created [duplicate]无法将字符串转换为我创建的枚举类型 [重复]
【发布时间】:2011-01-01 02:20:35
【问题描述】:

我有一个枚举:

public enum Color
{
    Red,
    Blue,
    Green,
}

现在,如果我将这些颜色作为文本字符串从 XML 文件中读取,如何将其转换为枚举类型 Color。

class TestClass
{
    public Color testColor = Color.Red;
}

现在,当使用像这样的文字字符串设置该属性时,编译器会发出非常严厉的警告。 :D 无法从字符串转换为颜色。

有什么帮助吗?

TestClass.testColor = collectionofstrings[23].ConvertToColor?????;

【问题讨论】:

    标签: c# string enums


    【解决方案1】:

    您正在寻找类似的东西吗?

    TestClass.testColor = (Color)Enum.Parse(typeof(Color), collectionofstrings[23]);
    

    【讨论】:

    • 无法将类型 Object 隐式转换为 Color(枚举)。在这种情况下我该怎么办?
    • @Sergio 那么你错过了明确的演员表(颜色)
    【解决方案2】:

    试试:

    TestClass.testColor = (Color)Enum.Parse(typeof(Color), collectionofstrings[23]);
    

    documentation about Enum

    编辑: 在 .NET 4.0 中,您可以使用一种类型更安全的方法(并且在解析失败时也不会抛出异常):

    Color myColor;
    if (Enum.TryParse(collectionofstring[23], out myColor))
    {
        // Do stuff with "myColor"
    }
    

    【讨论】:

    • 它说我无法从对象转换为颜色。有什么帮助吗?
    • 那么您可能在调用 Parse 之前忘记了对 Color 的强制转换。这肯定是从字符串到枚举的方法。
    • @MattGreer 如果您在解析“失败”时关心,这是一种更好的方法。确实,如果它实际上无法被解析,它不会抛出异常,而是它将返回枚举中的 0 条目是什么,你不知道它实际上失败了。
    【解决方案3】:

    您需要使用 Enum.Parse 将您的字符串转换为正确的 Color 枚举值:

    TestClass.testColor = (Color)Enum.Parse(typeof(Color), collectionofstrings[23], true);
    

    【讨论】:

      【解决方案4】:

      正如其他人所说:

      TestClass.testColor = (Color) Enum.Parse(typeof(Color), collectionofstrings[23]);
      

      如果您因为 collectionofstrings 是对象集合而遇到问题,请尝试以下操作:

      TestClass.testColor = (Color) Enum.Parse(
          typeof(Color), 
          collectionofstrings[23].ToString());
      

      【讨论】:

        猜你喜欢
        • 2015-11-09
        • 1970-01-01
        • 2021-07-21
        • 2012-12-07
        • 1970-01-01
        • 2018-02-14
        • 1970-01-01
        相关资源
        最近更新 更多