Cast object to a generic type

只谈情不闲聊 提交于 2020-01-02 01:24:08

问题


I haven't slept in a while so this is probably easier than I think it is.

I have a generic class that's more or less this:

public class Reference<T> where T : APIResource //<- APIResource is abstract btw
{
    private T _value = null;
    public T value
    { 
        get { return _value; }
    }
}

Elsewhere, in a custom serialize method, someone is passing in an object that is actually an instance of Reference<(something)>. I simply want to skip to the "value" property that every Reference<> object has, so I want to go:

string serialize(object o)
{
    return base.serialize( ((Reference<>) o).value );
}

Of course, life isn't that simple because as the compiler puts it:

using the generic type "Reference<T>" requires 1 type arguments

How can I do what I want to do?


回答1:


You can create a covariant generic interface with the property:

interface IReference<out T> where T : ApiResource {
    T Value { get; }
}

You can then cast IReference<Anything> to IReference<object> or IReference<ApiResource>.




回答2:


SLaks answer is perfect. I just want to extend it a little bit:

There are sometimes situations, where you can't substitute class with interface. Only in that cases you may want to use dynamic feature, so that you can call value property:

string serialize(object o)
{
    if(typeof(Reference<>) == o.GetType().GetGenericTypeDefinition())
        return base.serialize( ((dynamic)o).value );

    //in your case you will throw InvalidCastException
    throw new ArgumentException("not a Reference<>", "o"); 
}

This is just another options and I suggest to use it very carefully.




回答3:


Dont forget to check whether its generic type or not ---> o.GetType().IsGenericType, before

using o.GetType().GetGenericTypeDefinition() else it throws exception..



来源:https://stackoverflow.com/questions/16795750/cast-object-to-a-generic-type

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