简体   繁体   中英

Using Generic Types with As operator

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 doesn't work with value types (like int ) which T can be.

In this case, you just need a generic type parameter:

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

我想您要使用的is

 var isAThing = thing is Thing;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM