2009-09-01 13 views

Respuesta

52

Uso TypeOf...Is:

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

Tenga en cuenta que si "hacer cosas" requiere invocar a un miembro de la interfaz en el objeto, es probable que desee usar 'Como' para convertir y luego asegurarse de que el objeto 'No sea nada'. (Esto evita un segundo lanzamiento innecesario). – bobbymcr

3

requiredInterface.IsAssignableFrom (representedType)

tanto requiredInterface y representedType son tipos

3

También encontré este article por Scott Hansleman ser particularmente útil con esto. En ella, él recomienda

C#

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

que terminé haciendo:

VB.Net

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

Tengo un List(Of String) y la TypeOf tmp Is IList vuelve False. Una lista (Of T) implementa varias interfaces (IEnumerable, IList, ...) y el control de un solo requiere el siguiente fragmento en VB:

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

Aquí es una forma sencilla de determinar si una variable de objeto determinado "o "implementa una interfaz específica" ISomething ":

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