我想创建一个类型化和非类型化的接口,如IList和IList(Of T)。
我正在寻找的用法示例。
Dim a as IList(Of String)
test(a)
public sub test(value as IList){
//I can use the Ilist here without worrying that its an IList(Of String)
}
我想创建一个名为IRead的接口,我可以像IList接口一样使用它。
//我目前无法让这个工作 Msg(新测试())
有什么建议吗?
public Interface IRead(Of T)
Get() As T
End
public Interface IRead()
Get() as Object
End Interface
Public Class test
Implements IRead(Of Integer)
Public Function Get() As Integer Implements IRead(Of Integer).Get
Return 35235
End Function
End Class
private sub Msg(value as IRead)
MsgBox(value.GetSingle)
End Sub
答案 0 :(得分:1)
有两种方法可以做到这一点。首先,您可以单独定义两个接口,然后将其留给每个类来记住实现它们,如下所示:
Public Interface IRead
Function GetValue() As Object
End Interface
Public Interface IRead(Of T)
Function GetValue() As T
End Interface
Public Class MyReader
Implements IRead(Of Integer)
Implements IRead
Public Function GetValue() As Integer Implements IRead(Of Integer).GetValue
Return 35235
End Function
Private Function GetValueAsObject() As Object Implements IRead.GetValue
Return GetValue()
End Function
End Class
或者,如果要强制所有实现泛型接口的类也实现非泛型接口,可以通过让通用接口继承其他接口来实现,如下所示:
Public Interface IRead
Function GetValue() As Object
End Interface
Public Interface IRead(Of T)
Inherits IRead
Function GetValue() As T
End Interface
Public Class MyReader
Implements IRead(Of Integer)
Public Function GetValue() As Integer Implements IRead(Of Integer).GetValue
Return 35235
End Function
Private Function GetValueAsObject() As Object Implements IRead.GetValue
Return GetValue()
End Function
End Class
后一个选项很好,因为编译器不会让你忘记实现这两个接口,但它仍然不能让你不必在每个类中实现额外的传递方法。如果你想避免在每个类中编写额外的方法,唯一的方法是使用基类,例如:
Public MustInherit Class BaseReader(Of T)
Implements IRead(Of T)
Public MustOverride Function GetValue() As T Implements IRead(Of T).GetValue
Private Function GetValueAsObject() As Object Implements IRead.GetValue
Return GetValue()
End Function
End Class
Public Class MyReader
Inherits BaseReader(Of Integer)
Public Overrides Function GetValue() As Integer
Return 35235
End Function
End Class