说我有一个枚举,
public enum Colours
{
Red,
Blue
}
我能看到解析它们的唯一方法就是:
string colour = "Green";
var col = (Colours)Enum.Parse(typeOf(Colours),colour);
这将抛出System.ArgumentException因为“绿色”不是Colours
枚举的成员。
现在我真的讨厌在try / catch中包装代码,有没有更简洁的方法来执行此操作,不涉及我遍历每个Colours
枚举,并对colour
进行字符串比较?
答案 0 :(得分:55)
首先使用Enum.IsDefined()
,以避免包装在try / catch中。它将返回一个布尔值,表示输入是否是该枚举的有效成员。
答案 1 :(得分:41)
我认为4.0有 Enum.TryParse
否则使用extension method:
public static bool TryParse<T>(this Enum theEnum, string valueToParse, out T returnValue)
{
returnValue = default(T);
int intEnumValue;
if (Int32.TryParse(valueToParse, out intEnumValue))
{
if (Enum.IsDefined(typeof(T), intEnumValue))
{
returnValue = (T)(object)intEnumValue;
return true;
}
}
return false;
}
答案 2 :(得分:7)
只是扩展Sky的.Net 4 Enum.TryParse<>链接,即
Enum.TryParse<TEnum>(
string value,
[bool ignoreCase,]
out TEnum result
)
可以使用如下:
enum Colour
{
Red,
Blue
}
private void ParseColours()
{
Colour aColour;
// IMO using the actual enum type is intuitive, but Resharper gives
// "Access to a static member of a type via a derived type"
if (Colour.TryParse("RED", true, out aColour))
{
// ... success
}
// OR, the compiler can infer the type from the out
if (Enum.TryParse("Red", out aColour))
{
// ... success
}
// OR explicit type specification
// (Resharper: Type argument specification is redundant)
if (Enum.TryParse<Colour>("Red", out aColour))
{
// ... success
}
}
答案 3 :(得分:6)
不,这没有“禁止投掷”的方法(其他一些类的tryParse)。
但是,您可以轻松编写自己的代码,以便将try-catch逻辑(或IsDefined检查)封装在一个帮助程序方法中,这样就不会污染您的应用程序代码:
public static object TryParse(Type enumType, string value, out bool success)
{
success = Enum.IsDefined(enumType, value);
if (success)
{
return Enum.Parse(enumType, value);
}
return null;
}
答案 4 :(得分:6)
如果我正在解析“ trusted ”枚举,那么我使用Enum.Parse()。
通过“信任”,我的意思是,我知道它永远都是一个有效的枚举,而不会错过......永远!
但有时候“你永远不会知道你会得到什么”,而且在那些时候,你需要使用可以为空的返回值。由于.net不提供这种烘焙,你可以自己动手。这是我的食谱:
public static TEnum? ParseEnum<TEnum>(string sEnumValue) where TEnum : struct
{
TEnum eTemp;
TEnum? eReturn = null;
if (Enum.TryParse<TEnum>(sEnumValue, out eTemp) == true)
eReturn = eTemp;
return eReturn;
}
要使用此方法,请按以下方式调用:
eColor? SelectedColor = ParseEnum<eColor>("Red");
只需将此方法添加到用于存储其他常用实用程序函数的类中。