运营商'??'不能应用于'T'和'T'类型的操作数 [英] Operator '??' cannot be applied to operands of type 'T' and 'T'
问题描述
我有以下的泛型方法,但VS给了我一个编译错误。 (运算符'??'不能应用于'T'和'T'类型的操作数)
public static T Method< T(T模型)其中T:new()
{
var m = model?新的T();
}
有人知道为什么吗?
编辑:是否有可能原因是T可以是一个结构在我的情况,并且一个结构是一个非空类型?
您应该添加 class
约束:
$ b
public static T Method< T>(T model)其中T:class,new()
{
var m = model ??新T();
返回m;
}
您应该返回 m $ c $注意:由于@KristofDegrave在他的评论中提到,我们必须添加
class
约束是因为T可以是一个值类型,如 int
,并且自 ??
操作符(null-coalescing)检查类型可以为空,所以我们必须添加 class
约束来排除值类型。
编辑:Alvin Wong's答案也涵盖了可空类型的情况;这实际上是结构,但可以是操作数?运营商。请注意,如果没有Alvin的重载版本,对于可为空的类型, Method
将返回 null
。
I have the following generic method, but VS gives me a compile error on that. (Operator '??' cannot be applied to operands of type 'T' and 'T')
public static T Method<T>(T model) where T : new()
{
var m = model ?? new T();
}
Does some one have any idea why?
Edit: Is it possible the reason is that T can be a struct in my case, and a struct is an non-nullable type?
You should add class
constraint:
public static T Method<T>(T model) where T : class, new()
{
var m = model ?? new T();
return m;
}
And you should return m
too!
Note: As @KristofDegrave mentioned in his comment, the reason that we have to add class
constraint is because T can be a value type, like int
and since ??
operator (null-coalescing) check on types that can be null, so we have to add class
constraint to exclude value types.
Edit: Alvin Wong's answer covered the case for nullable types too; which are structs actually, but can be operands of ?? operator. Just be aware that Method
would return null
without Alvin's overloaded version, for nullable types.
这篇关于运营商'??'不能应用于'T'和'T'类型的操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!