当我试图使用泛型和as时,我会得到一个编译器错误。既然我不能用我想的方式去做,还有什么更好的方法..?我想检查5-6类型,计算出我可以使用一种方法,看看它是否为空。
T CheckIsType<T>(Thing thing)
{
return thing as T;
}
准确的错误文本:
Error 1 The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint.
发布于 2014-06-16 23:01:13
只需添加它抱怨不存在的约束:
T CheckIsType<T>(Thing thing)
where T: class
{
return thing as T;
}
发布于 2014-06-16 23:01:02
as
不能处理T可以是的值类型(如int
)。
在这种情况下,只需要一个泛型类型参数:
T CheckIsType<T>(Thing thing) where T: class
{
return thing as T;
}
发布于 2014-06-16 23:02:21
我想你想用is
代替。
var isAThing = thing is Thing;
https://stackoverflow.com/questions/24253439
复制相似问题