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.
The function may not internally use try
/catch
, which excludes using Enum.Parse
, which throws an exception when given an invalid argument.
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;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…