Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Say I have an enum,

public enum Colours
{
    Red,
    Blue
}

The only way I can see of parsing them is doing something like:

string colour = "Green";
var col = (Colours)Enum.Parse(typeOf(Colours),colour);

This will throw a System.ArgumentException because "Green" is not a member of the Colours enum.

Now I really hate wrapping code in try/catch's, is there no neater way to do this that doesn't involve me iterating through each Colours enum, and doing a string comparison against colour?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
346 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use Enum.IsDefined() first, to save yourself from wrapping in a try/catch. It will return a boolean value of whether or not the input is a valid member of that enum.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...