开发者

Cannot convert string to Enum type I created [duplicate]

开发者 https://www.devze.com 2022-12-15 03:58 出处:网络
This question already has answers here: Convert a string to an enum in C# (29 answers) Closed 9 years ago.
This question already has answers here: Convert a string to an enum in C# (29 answers) Closed 9 years ago.

I have an enum:

开发者_运维问答public enum Color
{
    Red,
    Blue,
    Green,
}

Now if I read those colors as literal strings from an XML file, how can I convert it to the enum type Color.

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

Now when setting that attribute by using a literal string like so, I get a very harsh warning from the compiler. :D Can't convert from string to Color.

Any help?

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


Is something like this what you're looking for?

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


Try:

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

See documentation about Enum

Edit: in .NET 4.0 you can use a more type-safe method (and also one that doesn't throw exceptions when parsing fails):

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


You need to use Enum.Parse to convert your string to the correct Color enum value:

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


As everyone else has said:

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

If you're having an issue because the collectionofstrings is a collection of objects, then try this:

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

精彩评论

暂无评论...
验证码 换一张
取 消