vb使用.Distinct和.ToList对.NET List对象进行子类化



我正试图通过对List(Of String)进行子类化来在VB.NET中实现StringList类。对于StringList类,大多数List方法都是不变的,但当该方法涉及迭代器时。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返回无法强制转换为StringListList(Of String)

实现Distinct()ToList()的正确方法是什么,这样我就可以使用StringList而不是泛型列表?

您应该编写自己的ToStringList方法。ToList是一个扩展方法,所以您也应该将ToStringList作为扩展方法来编写,扩展IEnumerable(Of String)

Damien_The_Unbeliever和jmcilinney指出了两种解决方案,但方式不同。使用哪个取决于您对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

jmcilinney的解决方案保留了StringList作为一个真正的类,并用一个产生StringList对象的方法扩展了IEnumerable(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.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

选择吧,感谢两位响应者。

相关内容

  • 没有找到相关文章

最新更新