繁体   English   中英

C#7.3枚举约束:为什么我不能使用可空的枚举?

[英]C# 7.3 Enum constraint: Why can't I use the nullable enum?

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

public static TResult? ToEnum<TResult>(this String value, TResult? defaultValue)
    where TResult : Enum
{
    return String.IsNullOrEmpty(value) ? defaultValue : (TResult?)Enum.Parse(typeof(TResult), value);
}

编译器说:

错误CS0453类型'TResult'必须是非可空值类型才能在泛型类型或方法'Nullable'中将其用作参数'T'

您可以,但必须添加另一个约束: struct约束。

public static void DoSomething<T>(T? defaultValue) where T : struct, Enum
{
}

因为System.Enum是一个类,所以不能声明Nullable<Enum>类型的变量(因为只有当Tstruct时才可以使用Nullable<T> )。

从而:

Enum? bob = null;

不会编译,你的代码也不会编译。

这绝对是奇怪的(因为Enum本身是一个类,但是你在代码中定义的特定Enum是一个struct )如果你以前没有遇到它,但它显然是一个class (不是struct ),因为docs和源代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM