不可用的枚举作为通用参数
我正在尝试在C#7.3中实现此辅助功能:
public static T? ToEnum<T>(this string enumName)
where T : Enum
=> Enum.TryParse<T>(enumName, out T val) ? val : null;
但是有一个编译器错误:
错误CS8370功能“无效的参考类型”在C#7.3
中不可用
为什么编译器认为我使用可确定的参考类型,而T则被限制为eNUM
哪个已经是值类型?
I am trying to implement this helper function in C# 7.3:
public static T? ToEnum<T>(this string enumName)
where T : Enum
=> Enum.TryParse<T>(enumName, out T val) ? val : null;
But got a compiler error:
Error CS8370 Feature 'nullable reference types' is not available in C# 7.3
Why does the compiler think I am using a nullable reference type while T is constrained to be an Enum
which is a value type already?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此问题不是特定于 nullable 枚举。即使您使用了不可用的枚举,它也行不通。这是因为虽然特定的枚举类型是价值类型,但
system.enum
是一种参考类型,如说明在这里。因此,除enum
约束外,您还需要添加struct
约束。以下内容应有效:
另外,请注意,您不能在三元运算符的第二个分支中使用
null
,因为编译器无法推断该类型。使用默认(t?)
而不是。用法的示例:
This problem is not specific to nullable enums. Even if you use a non-nullable enum, it won't work. That's because while specific enum types are value types,
System.Enum
is a reference type as explained here. So, you need to add astruct
constraint in addition to theEnum
constraint.The following should work:
Also, note that you can't use
null
in the second branch of the ternary operator because the compiler can't infer the type. Usedefault(T?)
instead.Example of usage: