我正在编写一些枚举功能,并具有以下内容:
public static T ConvertStringToEnumValue<T>(string valueToConvert,
bool isCaseSensitive)
{
if (String.IsNullOrWhiteSpace(valueToConvert))
return (T)typeof(T).TypeInitializer.Invoke(null);
valueToConvert = valueToConvert.Replace(" ", "");
if (typeof(T).BaseType.FullName != "System.Enum" &&
typeof(T).BaseType.FullName != "System.ValueType")
{
throw new ArgumentException("Type must be of Enum and not " +
typeof (T).BaseType.FullName);
}
if (typeof(T).BaseType.FullName == "System.ValueType")
{
return (T)Enum.Parse(Nullable.GetUnderlyingType(typeof(T)),
valueToConvert, !isCaseSensitive);
}
return (T)Enum.Parse(typeof(T), valueToConvert, !isCaseSensitive);
}
我现在用以下内容来称呼它:
EnumHelper.ConvertStringToEnumValue<Enums.Animals?>("Cat");
这可以按预期工作。但是,如果我运行这个:
EnumHelper.ConvertStringToEnumValue<Enums.Animals?>(null);
它打破了TypeInitializer为空的错误。
有谁知道如何解决这个问题?
全部谢谢!
答案 0 :(得分:9)
试
if (String.IsNullOrWhiteSpace(valueToConvert))
return default(T);
答案 1 :(得分:0)
我有一种不同的方法,使用扩展和泛型。
public static T ToEnum<T>(this string s) {
if (string.IsNullOrWhiteSpace(s))
return default(T);
s = s.Replace(" ", "");
if (typeof(T).BaseType.FullName != "System.Enum" &&
typeof(T).BaseType.FullName != "System.ValueType") {
throw new ArgumentException("Type must be of Enum and not " + typeof(T).BaseType.FullName);
}
if (typeof(T).BaseType.FullName == "System.ValueType")
return (T)Enum.Parse(Nullable.GetUnderlyingType(typeof(T)), s, true);
return (T)Enum.Parse(typeof(T), s, true);
}
像这样使用......
Gender? g = "Female".ToEnum<Gender?>();
答案 2 :(得分:0)
这个完成工作,看起来也很漂亮。希望它有所帮助!
/// <summary>
/// <para>More convenient than using T.TryParse(string, out T).
/// Works with primitive types, structs, and enums.
/// Tries to parse the string to an instance of the type specified.
/// If the input cannot be parsed, null will be returned.
/// </para>
/// <para>
/// If the value of the caller is null, null will be returned.
/// So if you have "string s = null;" and then you try "s.ToNullable...",
/// null will be returned. No null exception will be thrown.
/// </para>
/// <author>Contributed by Taylor Love (Pangamma)</author>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="p_self"></param>
/// <returns></returns>
public static T? ToNullable<T>(this string p_self) where T : struct
{
if (!string.IsNullOrEmpty(p_self))
{
var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
if (converter.IsValid(p_self)) return (T)converter.ConvertFromString(p_self);
if (typeof(T).IsEnum) { T t; if (Enum.TryParse<T>(p_self, out t)) return t;}
}
return null;
}
https://github.com/Pangamma/PangammaUtilities-CSharp/tree/master/src/StringExtensions