Generic Casting

…衆ロ難τιáo~ 提交于 2019-12-13 16:40:29

问题


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?


回答1:


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;
}


来源:https://stackoverflow.com/questions/9443951/generic-casting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!