How to see if a type implements an interface?

I need to know if a Type implements an interface.

 Dim asmRule As System.Reflection.Assembly = System.Reflection.Assembly.LoadFrom(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Rule.dll"))

 For Each typeAsm As System.Type In asmRule.GetTypes
     If TypeOf typeAsm Is Rule.IRule Then
       'that does always return false even though they implement IRule'
     End If
 Next

Thanks to all. Now i know why typeof didn't work. The type naturally does not implement IRule. I have filtered out two options from your answers:

  1. GetType(Rule.IRule).IsAssignableFrom(typeAsm)
  2. typeAsm.GetInterface(GetType(Rule.IRule).FullName) IsNot Nothing

What is the better choise according to performance?

UPDATE: i've found out that it might be better to use:

Not typeAsm.GetInterface(GetType(Rule.IRule).FullName) Is Nothing

instead of

GetType(Rule.IRule).IsAssignableFrom(typeAsm)

because the Interface IRule itself is assignable of IRule what raises a MissingMethodExcpetion if i try to create an instance:

ruleObj = CType(Activator.CreateInstance(typeAsm, True), Rule.IRule)

UPDATE2: Thanks to Ben Voigt. He convinced me that IsAssignableFrom in combination with IsAbstract might be the best way to check if a given type implements an interface and is not the interface itself (what throws a MissingMethodException if you try to create an instance).

If GetType(Rule.IRule).IsAssignableFrom(typeAsm) AndAlso Not typeAsm.IsAbstract Then
6
задан Tim Schmelter 17 July 2013 в 13:05
поделиться