的代码不同,这取决于你是否想知道,如果参考是基于一个通用型的原型,或专门的一个相当显着。
专业性的很容易,你可以只使用is
:
CheckType(IVehicle param)
{
var isofYourType = param is Car<int>;
...
}
或安全投,如图所示之前:你想知道
CheckType(IVehicle param)
{
var value = param as Car<int>;
if(value != null)
...
}
在案件是否尤尔VAR只是Car<T>
的一些专业化,事情变得非常难看。 而最后你应该的事情要担心的是速度在这种情况下,因为那会是比代码克甚至丑陋:
class Car<T>
{ }
interface IVehicle { }
class YourCar : Car<int>, IVehicle
{ }
static bool IsOfType(IVehicle param)
{
Type typeRef = param.GetType();
while (typeRef != null)
{
if (typeRef.IsGenericType &&
typeRef.GetGenericTypeDefinition() == typeof(Car<>))
{
return true;
}
typeRef = typeRef.BaseType;
}
return false;
}
static void Main(string[] args)
{
IVehicle test = new YourCar();
bool x = IsOfType(test);
}
你意味着汽车实施IVehicle? –
2008-11-07 15:15:31
刚编辑它。我的错。 – 2008-11-07 15:15:55