将Null转换为Nullable Enum(Generic)

Ric*_*ard 3 c# generics enums

我正在编写一些枚举功能,并具有以下功能:

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);
}
Run Code Online (Sandbox Code Playgroud)

我现在用以下内容称呼它:

EnumHelper.ConvertStringToEnumValue<Enums.Animals?>("Cat");
Run Code Online (Sandbox Code Playgroud)

这按预期工作.但是,如果我运行这个:

EnumHelper.ConvertStringToEnumValue<Enums.Animals?>(null);
Run Code Online (Sandbox Code Playgroud)

它打破了TypeInitializer为null的错误.

有谁知道如何解决这个问题?

谢谢大家!

Pre*_*gha 9

尝试

if (String.IsNullOrWhiteSpace(valueToConvert))
              return default(T);
Run Code Online (Sandbox Code Playgroud)