运算符“?”不能适用于类型的操作数“T” [英] Operator '?' cannot be applied to operand of type 'T'

查看:853
本文介绍了运算符“?”不能适用于类型的操作数“T”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图让功能通用,然后突然编译说

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; }
}



这是可能的,而不是使用此代码

It is possible to use this code instead

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.

推荐答案

由于不是什么都可以,你必须缩小 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.

添加其中,并解决这个问题:

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 运营商设置返回到键入 T 的值,它不能。如果 T INT 例如,它不能让它可以为空( INT <? / code>),因为实际需要的类型( 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);
}

这是不是空传播接线员会为你做。如果恢复使用默认(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天全站免登陆