我如何从接口 return 函数中输入 generic/dynamic
From an Interface how do I return a generic/dynamic type from a function
我想在界面中创建一个看起来像这样的函数;
Function GetRecords AS Ilist(of T)
当接口被实现时,我会设想 'T' 被用户或客户或供应商等取代。编译器显然不喜欢 T 本身指出它没有定义。我明白这一点,但肯定可以定义一些通用的东西。我试过使用 Type 但这会导致尴尬的类型转换。使用 Object 似乎更成功,但我找不到明确的最佳实践或示例。
虽然我使用 IList(of T) 作为示例,但它可以很容易地成为 IEnumerable(of T) 或 ICollection(of T)。我真的可以在界面中执行此操作吗?这将在 vb.net.
中完成
您需要像创建通用接口一样创建通用接口 class。
Public Interface IRecords(Of T)
Function GetRecords() As IList(Of T)
End Interface
用法:
Public Class Foo
Implements IRecords(Of Foo)
Public Function GetRecords() As IList(Of Foo) Implements IRecords(Of Foo).GetRecords
'Return ...
End Function
End Class
另一种选择是在 "normal" 接口内创建通用函数:
Public Interface IRecords
Function GetRecords(Of T)() As IList(Of T)
End Interface
用法:
Public Class Foo
Implements IRecords
Public Function GetRecords(Of T)() As IList(Of T) Implements IRecords.GetRecords
'Return ...
End Function
End Class
我想在界面中创建一个看起来像这样的函数;
Function GetRecords AS Ilist(of T)
当接口被实现时,我会设想 'T' 被用户或客户或供应商等取代。编译器显然不喜欢 T 本身指出它没有定义。我明白这一点,但肯定可以定义一些通用的东西。我试过使用 Type 但这会导致尴尬的类型转换。使用 Object 似乎更成功,但我找不到明确的最佳实践或示例。
虽然我使用 IList(of T) 作为示例,但它可以很容易地成为 IEnumerable(of T) 或 ICollection(of T)。我真的可以在界面中执行此操作吗?这将在 vb.net.
中完成您需要像创建通用接口一样创建通用接口 class。
Public Interface IRecords(Of T)
Function GetRecords() As IList(Of T)
End Interface
用法:
Public Class Foo
Implements IRecords(Of Foo)
Public Function GetRecords() As IList(Of Foo) Implements IRecords(Of Foo).GetRecords
'Return ...
End Function
End Class
另一种选择是在 "normal" 接口内创建通用函数:
Public Interface IRecords
Function GetRecords(Of T)() As IList(Of T)
End Interface
用法:
Public Class Foo
Implements IRecords
Public Function GetRecords(Of T)() As IList(Of T) Implements IRecords.GetRecords
'Return ...
End Function
End Class