重複の可能性:
C# で文字列を列挙型に変換するにはどうすればよいですか?
タイプintの列挙型があります:
public enum BlahType
{
blah1 = 1,
blah2 = 2
}
文字列がある場合:
string something = "blah1"
これを BlahType に変換するにはどうすればよいですか?
重複の可能性:
C# で文字列を列挙型に変換するにはどうすればよいですか?
タイプintの列挙型があります:
public enum BlahType
{
blah1 = 1,
blah2 = 2
}
文字列がある場合:
string something = "blah1"
これを BlahType に変換するにはどうすればよいですか?
このような関数を使用します
public static T GetEnumValue<T>(string value)
{
return (T)Enum.Parse(typeof(T), value);
}
そして、あなたはそれをこのように呼ぶことができます
BlahType value = GetEnumValue<BlahType>("Blah1");
Enum.Parseが必要です
BlahType blahValue = (BlahType) Enum.Parse(typeof(BlahType), something);
この関数を使用して、文字列を列挙型に変換します。次に、intなどにキャストできます。
public static T ToEnum<T>(string value, bool ignoreUpperCase)
where T : struct, IComparable, IConvertible, IFormattable {
Type enumType = typeof (T);
if (!enumType.IsEnum) {
throw new InvalidOperationException();
}
return (T) Enum.Parse(enumType, value, ignoreUpperCase);
}
public enum BlahType
{
blah1 = 1,
blah2 = 2
}
string something = "blah1";
BlahType blah = (BlahType)Enum.Parse(typeof(BlahType), something);
変換が成功するかどうかわからない場合は、代わりにTryParseを使用してください。