2010-06-30 64 views
2

我正在使用两种类型,一种是通用的,另一种不是。我没有对象的实例,但我想找出if (MyType is T)或者换句话说if (MyType inherits T)如何找出是否(类型是类型)C#

,我再次寻找:

if (Truck is Vehicle) 

if (MyTruckObject is Vehicle) 
+0

可能重复[如何判断一个实例是某个Type或任何派生类型](http://stackoverflow.com/questions/754858/how-to-tell-if-an-instance-is-of-a-certain-type-or-any -derived-types) – SwDevMan81 2010-06-30 15:34:04

+0

http://stackoverflow.com/questions/1433750/best-way-to-check-if-system-type-is-a-descendant-of-a-given-class – SwDevMan81 2010-06-30 15:36:26

+0

请注意, Type.IsSubclassOf ](http://msdn.microsoft.com/en-us/library/system.type.issubclassof.aspx)方法不适用于泛型类型! [**看看这篇文章**](http://www.pvladov.com/2012/05/get-all-derived-types-of-class.html)的IsSubclassOf方法的实现工作对于泛型也是如此。 – 2012-06-08 10:18:08

回答

5

尝试:

if (typeof(Truck).IsSubclassOf(typeof(Vehicle))) 
+0

相当吻合!谢谢! – 2010-06-30 15:40:54

2

嘛,给定一个泛型类型参数,你可以这样做:

if (typeof(Vehicle).IsAssignableFrom(typeof(T))) 
{ 

} 

或者应用约束的方法,以确保它:

public void DoSomething<T>() where T : Vehicle 
{ 

} 
相关问题