2008-11-07 41 views
0

如果我有一個參數是一個接口的方法,請問如果接口的引用是特定泛型類型的快速方法是什麼?什麼是檢查該引用是否爲特定泛型類型的快速方法?

更具體地說,如果我有:

interface IVehicle{} 

class Car<T> : IVehicle {} 

CheckType(IVehicle param) 
{ 
    // How do I check that param is Car<int>? 
} 

我也將不得不在檢查後才能投放。所以如果有一種方法可以在這一塊上一箭雙鵰,那就讓我知道。

+0

你意味着汽車實施IVehicle? – 2008-11-07 15:15:31

+0

剛編輯它。我的錯。 – 2008-11-07 15:15:55

回答

10

要檢查如果param是Car<int>你可以用「是」和「爲」正常:

CheckType(IVehicle param) 
{ 
    Car<int> car = param as Car<int>; 
    if (car != null) 
    { 
     ... 
    } 
} 
+0

Jon - 你的C#書很有幫助 - 感謝你和DNR的精彩採訪。鑑於我的歷史與你的建議,我傾向於盲目相信你!話雖如此,爲什麼尼克的反應(直接使用)是更好的方法呢? – 2008-11-07 15:52:04

0

我經常發現,如果我的代碼需要我寫檢查特定類型的,我可能做錯了什麼。雖然你沒有給我們足夠的背景給我們提供建議。

這是否符合您的需求?

Car<int> carOfInt = param as Car<int>; 
if (carOfInt != null) 
{ 
    // .. yes, it's a Car<int> 
} 
0

使用「as」操作符一次性完成所有操作。 「as」將返回所需類型的對象,如果您檢查的內容不匹配,則返回null。但這隻適用於參考類型。

interface IVehicle { } 
class Car<T> : IVehicle 
{ 
    static Car<int> CheckType(IVehicle v) 
    { 
     return v as Car<int>; 
    } 
} 

的「是」運營商將讓你測試,看看是否vCar<int>一個實例。

3

或者,你可以這樣做:

if(param is Car<int>) 
{ 
    // Hey, I'm a Car<int>! 
} 
1

爲什麼不把這個通用的?

interface IVehicle{} 

class Car<T> : IVehicle { 

    public static bool CheckType(IVehicle param) 
    { 
     return param is Car<T>; 
    } 
} 

...

Car<string> c1 = new Car<string>(); 
Car<int> c2 = new Car<int>(); 
Console.WriteLine(Car<int>.CheckType(c1)); 
Console.WriteLine(Car<int>.CheckType(c2)); 
1

的代碼不同,這取決於你是否想知道,如果參考是基於一個通用型的原型,或專門的一個相當顯着。

專業性的很容易,你可以只使用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); 
} 
相關問題