Ho un parametro oggetto e devo verificare se l'oggetto implementa un'interfaccia specifica in vb.net. Come testarlo?Verifica se un oggetto implementa un'interfaccia
Grazie.
Ho un parametro oggetto e devo verificare se l'oggetto implementa un'interfaccia specifica in vb.net. Come testarlo?Verifica se un oggetto implementa un'interfaccia
Grazie.
Uso TypeOf...Is:
If TypeOf objectParameter Is ISpecifiedInterface Then
'do stuff
End If
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
requiredInterface.IsAssignableFrom (representedType)
sia requiredInterface e representedType sono tipi
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
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
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
Questa è una grande domanda, corrisponde esattamente alla mia query di ricerca in google e ha una risposta. – CodingBarfield