C# 7.3 枚举约束 : Why can't I use the nullable enum?

标签 c# enums roslyn c#-7.3

既然我们有了枚举约束,为什么编译器不允许我编写这段代码?

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/

相关文章:

c# - 服务器端 Blazor 中单个 EditForm 中的多个模型验证

c# - 在 Roslyn 中使用 System.Dynamic

c# - 使用roslyn编译Xaml得到*.g.cs文件

c# - 如何在 C# Windows 窗体中使用 linq 在组合框中显示多个字段?

c# - 如何将 List<int> 转换为 string[]?

c# - 调用 Windows Phone 8.1 ContactManager.RequestStoreAsync() 时出现访问被拒绝异常;

python - 使用枚举 Django 的下拉菜单主题

c++ - Doxygen 不会为不在类里面的枚举生成文档

java - 如何在Java中创建类似于 "dynamic enumerations"的常量分组?

c# - 为什么 PreIncrement 类型的 PrefixUnaryExpressionSyntax 允许使用 ParanthesisedExpressionsSyntax 的操作数?