开发者

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 
{

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜