2009-09-01 11 views

risposta

52

Uso TypeOf...Is:

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

Si noti che se "do stuff" richiede il richiamo di un membro dell'interfaccia sull'oggetto, probabilmente si desidera utilizzare "As" per eseguire il cast e quindi assicurarsi che l'oggetto "IsNot Nothing". (Questo impedisce un secondo cast non necessario.) – bobbymcr

3

requiredInterface.IsAssignableFrom (representedType)

sia requiredInterface e representedType sono tipi

3

Ho trovato anche questo article da Scott Hansleman ad essere particolarmente utile con questo. In esso, egli raccomanda

C#

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

ho finito per fare:

VB.Net

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

Ho un List(Of String) e la TypeOf tmp Is IList rendimenti False. Un elenco (Of T) implementa più interfacce (IEnumerable, IList, ...) e controllando un solo richiede il seguente frammento in VB:

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

Ecco un modo semplice per determinare se una data variabile oggetto "o "implementa un'interfaccia specifica" ISomething ":

If o.GetType().GetInterfaces().Contains(GetType(ISomething)) Then 
    ' The interface is implemented 
End If 
Problemi correlati