如何尝试解析枚举值? [英] How to TryParse for Enum value?
问题描述
我想编写一个函数,该函数可以根据 enum
的可能值验证给定值(作为字符串传递).在匹配的情况下,它应该返回枚举实例;否则,它应该返回一个默认值.
I want to write a function which can validate a given value (passed as a string) against possible values of an enum
. In the case of a match, it should return the enum instance; otherwise, it should return a default value.
函数内部不能使用try
/catch
,不包括使用Enum.Parse
,当给定无效参数时会抛出异常.
The function may not internally use try
/catch
, which excludes using Enum.Parse
, which throws an exception when given an invalid argument.
我想使用类似于 TryParse
函数的内容来实现这一点:
I'd like to use something along the lines of a TryParse
function to implement this:
public static TEnum ToEnum<TEnum>(this string strEnumValue, TEnum defaultValue)
{
object enumValue;
if (!TryParse (typeof (TEnum), strEnumValue, out enumValue))
{
return defaultValue;
}
return (TEnum) enumValue;
}
推荐答案
正如其他人所说,您必须实现自己的 TryParse
.Simon Mourier 提供了一个完整的实现,可以处理所有事情.
As others have said, you have to implement your own TryParse
. Simon Mourier is providing a full implementation which takes care of everything.
如果您使用位域枚举(即标志),您还必须处理像 "MyEnum.Val1|MyEnum.Val2"
这样的字符串,它是两个枚举值的组合.如果你只是用这个字符串调用 Enum.IsDefined
,它会返回 false,即使 Enum.Parse
正确处理它.
If you are using bitfield enums (i.e. flags), you also have to handle a string like "MyEnum.Val1|MyEnum.Val2"
which is a combination of two enum values. If you just call Enum.IsDefined
with this string, it will return false, even though Enum.Parse
handles it correctly.
更新
正如 Lisa 和 Christian 在评论中提到的,Enum.TryParse
现在可用于 .NET4 及更高版本的 C#.
MSDN 文档
As mentioned by Lisa and Christian in the comments, Enum.TryParse
is now available for C# in .NET4 and up.
MSDN Docs
这篇关于如何尝试解析枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!