我试图通过继承List(Of String)在VB.NET中实现StringList类。对于StringList类,大多数List方法都没有改变,但是当该方法涉及iterator.ToList()时,结果是一个通用列表,无法下载回该类。
考虑代码:
Module Module1
Sub Main()
Dim a0 As New List(Of String) From {"Apple", "Banana", "Cherry", "Banana"}
Dim b0 As New StringList From {"Asparagus", "Broccoli", "Cucumber", "Broccoli"}
Dim a1 As List(Of String) = a0.Distinct.ToList ' list of 3 strings
Dim b1 As StringList = b0.Distinct.ToList ' runtime exception invalid cast from List(Of String) to StringList
End Sub
End Module
Class StringList
Inherits List(Of String)
Public Overrides Function ToString() As String
Return Strings.Join(Me.ToArray, ", ")
End Function
End Class
b1
分配将失败,因为.Distinct
返回迭代器而.ToList
返回List(Of String)
,无法转换为StringList
。
实施Distinct()
或ToList()
的正确方法是什么,以便我可以使用StringList
代替通用列表?
答案 0 :(得分:0)
您应该编写自己的ToStringList
方法。 ToList
是一种扩展方法,因此您也应将ToStringList
作为扩展方法编写,扩展IEnumerable(Of String)
。
答案 1 :(得分:0)
Damien_The_Unbeliever和jmcilhinney已经指出了解决方案,这两种方法都有效,但方式不同。您使用哪个取决于您的StringList
类的偏好和未来计划,但两者都不是完全干净的,因为代码不可知您是否使用List(Of String)
或StringList
Damien_The_Unbeliever的解决方案取消StringList
课程,将其降级为Imports
,并延伸List(Of String)
:
Imports StringList = System.Collections.Generic.List(Of String)
Module Module1
Sub Main()
Dim a0 As New List(Of String) From {"Apple", "Banana", "Cherry", "Banana"}
Dim b0 As New StringList From {"Asparagus", "Broccoli", "Cucumber", "Broccoli"}
Dim a1 As List(Of String) = a0.Distinct.ToList ' list of 3 strings
Dim b1 As StringList = b0.Distinct.ToList ' likewise
Console.WriteLine(b1.ToString2()) ' works, but you can't override ToString()
End Sub
<System.Runtime.CompilerServices.Extension()>
Public Function ToString2(ByVal s As StringList) As String
Return Strings.Join(s.ToArray, ", ")
End Function
End Module
jmcilhinney的解决方案将StringList
保留为真正的类,并使用生成IEnumerable(Of String)
对象的方法扩展StringList
:
Module Module1
Sub Main()
Dim a0 As New List(Of String) From {"Apple", "Banana", "Cherry", "Banana"}
Dim b0 As New StringList From {"Asparagus", "Broccoli", "Cucumber", "Broccoli"}
Dim a1 As List(Of String) = a0.Distinct.ToList ' list of 3 strings
Dim b1 As StringList = b0.Distinct.ToStringList ' works, but you can't use ToList()
Console.WriteLine(b1.ToString())
End Sub
<System.Runtime.CompilerServices.Extension()>
Public Function ToStringList(ByVal sl As IEnumerable(Of String)) As StringList
Dim ret As New StringList From {}
For Each i As String In sl
ret.Add(i)
Next
Return ret
End Function
End Module
Class StringList
Inherits List(Of String)
Public Overrides Function ToString() As String
Return Strings.Join(Me.ToArray, ", ")
End Function
End Class
接受你的选择,并感谢两位回应者。