既然我们有了枚举约束,为什么编译器不允许我编写这段代码?
public static TResult? ToEnum<TResult>(this String value, TResult? defaultValue)
where TResult : Enum
{
return String.IsNullOrEmpty(value) ? defaultValue : (TResult?)Enum.Parse(typeof(TResult), value);
}
编译器说:
Error CS0453 The type 'TResult' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable'
最佳答案
可以,但必须添加另一个约束:struct
约束。
public static void DoSomething<T>(T? defaultValue) where T : struct, Enum
{
}
关于C# 7.3 枚举约束 : Why can't I use the nullable enum?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50351594/