I've come across the situation on a number of occasions when coding where I've wanted to convert from a string to an enum. In the Media Catalog sample, I resorted to one giant switch statement that has a case block for each string that returns an enum from it.
One of my colleagues came up with the answer yesterday; it's one of those methods that you can never find when you're looking for it, but once discovered it seems blindingly obvious:
object Enum.Parse(System.Type enumType, string value, bool ignoreCase);
So you can write the following kind of code:
enum Colour { Red, Green, Blue } // ... Colour c = (Colour) Enum.Parse(typeof(Colour), "Red", true); Console.WriteLine("Colour Value: {0}", c.ToString()); // Picking an invalid colour throws an ArgumentException. To // avoid this, call Enum.IsDefined() first, as follows: string nonColour = "Polkadot"; if (Enum.IsDefined(typeof(Colour), nonColour)) c = (Colour) Enum.Parse(typeof(Colour), nonColour, true); else MessageBox.Show("Uh oh!");
What a time saver - thanks, Simon!
Footnote: interestingly, whilst writing this up I noticed that Enum.IsDefined() doesn’t offer the ignoreCase parameter. If you don’t know whether the casing is right, it seems the only way to do the conversion is using the Parse method and catching the ArgumentException. That's not ideal, since it runs a lot slower. I wonder if this is a loophole in the design; no doubt someone like Brad could cast light on it...
posted on Friday, April 02, 2004 1:49 PM
Feedback
# re: How do you convert a string into an enum? 4/2/2004 7:22 PM SBC
You can get the string values of enums also by calling Enum.GetNames or Enum.GetName...
'Unity > 스크립트' 카테고리의 다른 글
Android 국가코드 정보 (0) | 2015.06.07 |
---|---|
에셋 Android Native Plugins에 대해 (0) | 2015.03.02 |
기본 변수 저장시 암호화 (0) | 2014.10.16 |
Playerprefs 암호화. (0) | 2014.10.14 |
어떤한 물체가 다른 물체의 공간안에 완벽히 들어와 있는가를 체크하는 공식 (0) | 2014.06.11 |
WRITTEN BY