Operator #39;?#39; cannot be applied to operand of type #39;T#39;(操作员 ?不能应用于“T类型的操作数)
问题描述
试图使 Feature 泛型然后突然编译器说
Trying to make Feature generic and then suddenly compiler said
运算符'?'不能应用于T"类型的操作数
这里是代码
public abstract class Feature<T>
{
public T Value
{
get { return GetValue?.Invoke(); } // here is error
set { SetValue?.Invoke(value); }
}
public Func<T> GetValue { get; set; }
public Action<T> SetValue { get; set; }
}
可以改用这段代码
get
{
if (GetValue != null)
return GetValue();
return default(T);
}
但我想知道如何修复那个漂亮的 C# 6.0 单线.
But I am wondering how to fix that nice C# 6.0 one-liner.
推荐答案
由于不是所有的东西都可以为 null,你必须缩小 T 为可以为空的东西(又名对象).结构不能为空,枚举也不能.
Since not everything can be null, you have to narrow down T to be something nullable (aka an object). Structs can't be null, and neither can enums.
在 class 上添加 where 确实可以解决问题:
Adding a where on class does fix the issue:
public abstract class Feature<T> where T : class
那么为什么它不能正常工作呢?
So why doesn't it just work?
Invoke() 产生 T.如果 GetValue 为 null,则 ? 运算符将 T 类型的返回值设置为 null代码>,它不能.例如,如果 T 是 int,它不能使其为空 (int?),因为需要的实际类型 (T = int) 不是.
Invoke() yields T. If GetValue is null, the ? operator sets the return value of type T to null, which it can't. If T is int for example, it can't make it nullable (int?) since the actual type required (T = int) isn't.
如果你把代码中的T改为int,你就会很清楚的看到问题所在.你问的最终结果是这样的:
If you change T to be int in your code, you will see the problem very clearly. The end result of what you ask is this:
get
{
int? x = GetValue?.Invoke();
return x.GetValueOrDefault(0);
}
这不是空传播运算符将为您做的事情.如果您恢复使用 default(T) 它确实知道该做什么,并且您避免了有问题的"空传播.
This is not something the null-propagation operator will do for you. If you revert to the use of default(T) it does know exactly what to do and you avoid the 'problematic' null-propagation.
这篇关于操作员 '?'不能应用于“T"类型的操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:操作员 '?'不能应用于“T"类型的操作数
基础教程推荐
- 如果条件可以为空 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 将数据集转换为列表 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
