C#7.3枚举约束:为什么我不能使用可为空的枚举? [英] C# 7.3 Enum constraint: Why can't I use the nullable enum?

查看:372
本文介绍了C#7.3枚举约束:为什么我不能使用可为空的枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我们有了枚举约束,为什么编译器不允许我编写此代码?

Now that we have enum constraint, why doesn't compiler allow me to write this code?

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"必须是不可为空的值类型,以便在通用类型或方法可为空"中将其用作参数"T"

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约束.

You can, but you have to add another constraint: the struct constraint.

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

这篇关于C#7.3枚举约束:为什么我不能使用可为空的枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆