接线员’?’ 不能应用于’T’类型的操作数
试图使Feature
通用,然后突然编译说
接线员’?’ 不能应用于’T’类型的操作数
这是代码
public abstract class Feature { public T Value { get { return GetValue?.Invoke(); } // here is error set { SetValue?.Invoke(value); } } public Func GetValue { get; set; } public Action SetValue { get; set; } }
可以使用此代码
get { if (GetValue != null) return GetValue(); return default(T); }
但我想知道如何修复那个漂亮的C#6.0单线程。
因为并非所有东西都可以为null
,所以你必须将T
缩小为可以为空的(也就是object
)。 结构不能为空,也不能枚举。
在class
上添加where
会解决问题:
public abstract class Feature where T : class
那为什么它不起作用呢?
Invoke()
产生T
如果GetValue
为null
,那么?
operator将类型T
的返回值设置为null
,但不能。 例如,如果T
为int
,则它不能使其为空( int?
),因为所需的实际类型( T
= int
)不是。
如果在代码中将T
更改为int
,则会非常清楚地看到问题。 你问的最终结果如下:
get { int? x = GetValue?.Invoke(); return x.GetValueOrDefault(0); }
这不是零传播运算符将为您做的事情。 如果你恢复使用default(T)
它确实知道该怎么做,你就避免了“有问题”的零传播。
T
必须是引用类型或可空类型
public abstract class Feature where T : class { // ... }
据我所知?.
operator是硬编码的,可以使用null
,也就是说,它适用于引用类型或可空值类型,但不适用于普通值类型。 如果表达式为null
而不是default(T)
,则运算符可能会返回null
。
您可以通过在此限制T
到class
来修复它。