2010-06-30 65 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 
{ 

} 
相關問題