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