简体   繁体   中英

Generic Casting

I suspect the answer is no, but is it possible to do something like this in C#.NET (v2.0).

class Converter<E>
{
    public E Make(object o)
    {
        return o as E;
    }
}

If not, is it possible to check types like this:

public bool IsType(object o, Type t)
{
    return o is E;
}

I'm not certain about the terminology so it is rather hard to Google for me. But my guess is that these two problems are related. Any ideas?

You can cast o to E using the () Operator :

class Converter<E>
{
    public E Make(object o)
    {
        return (E)o;
    }
}

If you use as , o as E requires E to a be a reference type, because if o is not castable to E , the result is (E)null . You can constrain E to reference types by using the class Constraint :

class Converter<E> where E : class
{
    public E Make(object o)
    {
        return o as E;
    }
}

public bool IsType(object o, Type t)
{
    return (o != null) ? t.IsAssignableFrom(o.GetType()) : t.IsClass;
}

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