使用泛型与As运算符 [英] Using Generic Types with As operator

查看:350
本文介绍了使用泛型与As运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用as与generic时出现编译器错误。既然我不能按照我想要的方式来做,那么更好的方法是什么......?我想检查5-6种类型,确定我可以使用一种方法,看看它是否为空。

I get a compiler error when Trying to use a generic with as. Since i can't do it the way I want to, what is a better way..? I wanted to check through 5-6 types, figuring i can use one method and see if it is null or not.

    T CheckIsType<T>(Thing thing)
    {
        return thing as T;
    }

确切的错误文字:

exact error text:

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.


推荐答案

只需添加抱怨不存在的约束:

Just add the constraint it's complaining about not being there:

T CheckIsType<T>(Thing thing)
    where T: class
{
    return thing as T;
}

这篇关于使用泛型与As运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆