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"类型的操作数
基础教程推荐
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- WPF 模态进度窗口 2022-01-01
