[英]Using Generic Types with As operator
尝试与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.
只需添加它抱怨不在那里的约束即可:
T CheckIsType<T>(Thing thing)
where T: class
{
return thing as T;
}
as
不适用于T可以的值类型(例如int
)。
在这种情况下,您只需要一个泛型类型参数:
T CheckIsType<T>(Thing thing) where T: class
{
return thing as T;
}
我想您要使用的is
。
var isAThing = thing is Thing;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.