的代碼不同,這取決於你是否想知道,如果參考是基於一個通用型的原型,或專門的一個相當顯着。
專業性的很容易,你可以只使用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