2009-09-01 105 views

回答

52

使用TypeOf...Is

If TypeOf objectParameter Is ISpecifiedInterface Then 
    'do stuff 
End If 
+1

請注意,如果「do stuff」需要調用對象的接口成員,那麼可能需要使用「As」進行強制轉換,然後確保對象「IsNot Nothing」。 (這可以防止不必要的第二次演員。) – bobbymcr 2009-09-01 03:34:29

3

requiredInterface.IsAssignableFrom(representedType)

兩個requiredInterface和representedType是類型

3

我也發現了這個article斯科特Hansleman是這個特別有幫助。在書中,他建議

C#

if (typeof(IWhateverable).IsAssignableFrom(myType)) { ... } 

我落得這樣做:

VB.Net

Dim _interfaceList As List(Of Type) = myInstance.GetType().GetInterfaces().ToList() 
If _interfaceList.Contains(GetType(IMyInterface)) Then 
    'Do the stuff 
End If 
0

我有一個List(Of String)TypeOf tmp Is IList回報False。一覽表(Of T)已實現了多個接口(IEnumerable的,IList的,...),並檢查只是一個需要VB下面的代碼片段:

If tmp.GetInterfaces().Contains(GetType(IEnumerable)) Then 
    // do stuff... 
End If 
1

這裏有一個簡單的方法來確定是否一個給定對象變量的「o 「實現一個特定的接口」ISomething「:

If o.GetType().GetInterfaces().Contains(GetType(ISomething)) Then 
    ' The interface is implemented 
End If 
相關問題