测试一个对象是否实现了一个接口
答
使用TypeOf...Is:
If TypeOf objectParameter Is ISpecifiedInterface Then
'do stuff
End If
+1
请注意,如果“do stuff”需要调用对象的接口成员,那么可能需要使用“As”进行强制转换,然后确保对象“IsNot Nothing”。 (这可以防止不必要的第二次演员。) – bobbymcr 2009-09-01 03:34:29
答
requiredInterface.IsAssignableFrom(representedType)
两个requiredInterface和representedType是类型
答
我也发现了这个article斯科特Hansleman是这个特别有帮助。在书中,他建议
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
答
我有一个List(Of String)
和TypeOf tmp Is IList
回报False
。一览表(Of T)已实现了多个接口(IEnumerable的,IList的,...),并检查只是一个需要VB下面的代码片段:
If tmp.GetInterfaces().Contains(GetType(IEnumerable)) Then
// do stuff...
End If
答
这里有一个简单的方法来确定是否一个给定对象变量的“o “实现一个特定的接口”ISomething“:
If o.GetType().GetInterfaces().Contains(GetType(ISomething)) Then
' The interface is implemented
End If
这是一个很好的问题,我的搜索查询完全匹配谷歌,并有一个答案。 – CodingBarfield 2011-02-03 15:56:29