问题
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