【发布时间】:2013-06-06 12:51:24
【问题描述】:
我最近为我实现的一些自定义用户控件添加了一个界面。界面非常基本。它有一种支持链接的方法:
Public Interface IMyInterface(Of T As WebControl)
Function DoSomething() As T
End Interface
实现也很基本:
Public Class MyCustomControl
Inherits CompositeControl
Implements IMyInterface(Of MyCustomControl)
Public Function DoSomething() As MyCustomControl _
Implements IMyInterface(Of MyCustomControl).DoSomething
' do stuff
Return Me
End Class
到目前为止一切正常。当我尝试遍历所有实现 IMyInterface 接口的控件集合时,就会出现问题,如下所示:
Dim myList = New List(Of IMyInterface(Of WebControl))
myList.Add(someCustomControl)
myList.ForEach(Sub(i) i.DoSomething())
someCustomControl 是一个MyCustomControl,它实现了IMyInterface(Of MyCustomControl) 而不是IMyInterface(Of WebControl)。
我在第二行(我尝试添加someCustomControl)收到此错误:
Option Strict On 不允许从“MyCustomControl”到“IMyInterface(Of WebControl)”的隐式转换。
有什么办法可以绕过这个错误吗?我接近让它工作了,但我对泛型的了解还不够,无法超越这一点。
【问题讨论】:
-
当您尝试像
Dim myList = New List(Of IMyInterface(Of WebControl))一样声明 myList 时,请尝试使用Dim myList = New List(Of Object)或类似的东西。 -
@Vishal 我认为如果没有
IMyInterface类型,您将无法在ForEach循环中的对象上调用DoSomething()。 -
对不起,我不知道。
标签: vb.net generics interface user-controls