我正在使用两种类型,一种是通用的,另一种不是。我没有对象的实例,但我想找出if (MyType is T)
或者换句话说if (MyType inherits T)
如何找出是否(类型是类型)C#
,我再次寻找:
if (Truck is Vehicle)
不
if (MyTruckObject is Vehicle)
我正在使用两种类型,一种是通用的,另一种不是。我没有对象的实例,但我想找出if (MyType is T)
或者换句话说if (MyType inherits T)
如何找出是否(类型是类型)C#
,我再次寻找:
if (Truck is Vehicle)
不
if (MyTruckObject is Vehicle)
尝试:
if (typeof(Truck).IsSubclassOf(typeof(Vehicle)))
相当吻合!谢谢! – 2010-06-30 15:40:54
嘛,给定一个泛型类型参数,你可以这样做:
if (typeof(Vehicle).IsAssignableFrom(typeof(T)))
{
}
或者应用约束的方法,以确保它:
public void DoSomething<T>() where T : Vehicle
{
}
的
可能重复[如何判断一个实例是某个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
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
请注意, 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