How to find out if (Type is Type) C#
I am working with two types, one generic and the other not. I don't have instances of objects but I want to find out if ( MyType is T )
or in other words if ( MyType inherits T)
Again, I am looking for:
if ( Truck is Vehicle )
not
if ( MyTruckObject is开发者_如何学运维 Vehicle)
Type.IsSubclassOf
try:
if (typeof(Truck).IsSubclassOf(typeof(Vehicle)))
Well, given a generic type argument, you could do something like:
if (typeof(Vehicle).IsAssignableFrom(typeof(T)))
{
}
Or, apply a constraint to a method to ensure it:
public void DoSomething<T>() where T : Vehicle
{
}
精彩评论