测试对象是否实现了接口

时间:2009-09-01 02:31:19

标签: vb.net

我有一个对象参数,我需要检查对象是否在vb.net中实现了指定的接口。如何测试?

感谢。

5 个答案:

答案 0 :(得分:56)

使用TypeOf...Is

If TypeOf objectParameter Is ISpecifiedInterface Then
    'do stuff
End If 

答案 1 :(得分:6)

我还发现Scott Hansleman对此article特别有帮助。在其中,他建议

<强> 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

答案 2 :(得分:3)

requiredInterface.IsAssignableFrom(representedType)

requiredInterface和representType都是Types

答案 3 :(得分:2)

这是确定给定对象变量“o”是否实现特定接口“ISomething”的简单方法:

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

答案 4 :(得分:0)

我有List(Of String)TypeOf tmp Is IList返回False。 List(Of T)实现多个接口(IEnumerable,IList,...),只检查一个接口需要VB中的以下片段:

If tmp.GetInterfaces().Contains(GetType(IEnumerable)) Then
  // do stuff...
End If
相关问题