使用泛型类型和As操作符

本文关键字:As 操作符 泛型类型 | 更新日期: 2023-09-27 18:08:57

当尝试使用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.

使用泛型类型和As操作符

只需添加约束它会抱怨不在那里:

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;