操作员 '?'不能应用于“T"类型的操作数 [英] Operator '?' cannot be applied to operand of type 'T'

查看:17
本文介绍了操作员 '?'不能应用于“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.如果 GetValuenull,则 ? 运算符将 T 类型的返回值设置为 null,它不能.例如,如果 Tint,它不能使其为空 (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"类型的操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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