VB.NET ArrayList 到 List(Of T) 类型的复制/转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3555970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 15:01:06  来源:igfitidea点击:

VB.NET ArrayList to List(Of T) typed copy/conversion

vb.nettype-conversion

提问by vulkanino

I have a 3rd party method that returns an old-style ArrayList, and I want to convert it into a typed ArrayList(Of MyType).

我有一个返回旧式 ArrayList 的第 3 方方法,我想将其转换为类型化的 ArrayList(Of MyType)。

Dim udc As ArrayList = ThirdPartyClass.GetValues()
Dim udcT AS List(Of MyType) = ??

I have made a simple loop, but there must be a better way:

我做了一个简单的循环,但一定有更好的方法:

Dim udcT As New List(Of MyType)
While udc.GetEnumerator.MoveNext
    Dim e As MyType = DirectCast(udc.GetEnumerator.Current, MyType)
    udcT.Add(e)
End While

回答by Mehrdad Afshari

Dim StronglyTypedList = OriginalArrayList.Cast(Of MyType)().ToList()
' requires `Imports System.Linq`

回答by Tim Schmelter

Duplicate. Have a look at this SO-Thread: In .Net, how do you convert an ArrayList to a strongly typed generic list without using a foreach?

复制。看看这个 SO-Thread:在 .Net 中,如何在不使用 foreach 的情况下将 ArrayList 转换为强类型泛型列表?

In VB.Net with Framework < 3.5:

在框架 < 3.5 的 VB.Net 中:

Dim arrayOfMyType() As MyType = DirectCast(al.ToArray(GetType(MyType)), MyType())
Dim strongTypeList As New List(Of MyType)(arrayOfMyType)

回答by vulkanino

What about this?

那这个呢?

Public Class Utility

    Public Shared Function ToTypedList(Of C As {ICollection(Of T), New}, T)(ByVal list As ArrayList) As C

        Dim typedList As New C
        For Each element As T In list
            typedList.Add(element)
        Next

        Return typedList
    End Function

End Class

If would work for any Collection object.

如果适用于任何 Collection 对象。

回答by kingfrito_5005

I would like to point out something about both the DirectCast and System.Linq.Cast (which are the same thing in the latest .NET at least.) These may not work if the object type in the array is defined by the user class, and is not easily convertable into object types that .NET recognizes. I do not know why this is the case, but it seems to be the problem in the software for which I am developing, and so for these we have been forced to use the inelegant loop solution.

我想指出一些关于 DirectCast 和 System.Linq.Cast(至少在最新的 .NET 中是相同的东西。)如果数组中的对象类型是由用户类定义的,这些可能不起作用,并且不容易转换为 .NET 识别的对象类型。我不知道为什么会这样,但这似乎是我正在开发的软件中的问题,因此对于这些我们不得不使用不雅的循环解决方案。