克隆不能实现 ICloneable 的引用类型列表

发布于 2024-09-24 10:45:01 字数 455 浏览 0 评论 0原文

是否有一种更简单/更简洁的方法来深度克隆未实现 ICloneable 的引用类型列表。

目前已经循环遍历列表中的每个对象,如下所示:

    Dim myListCopy As New List(Of ListObj)
    For Each lo As ListObj In MyList
        myListCopy.Add(lo.ShallowCopy)
    Next

对象 ListObj 仅包含值类型并返回浅成员。

这有效,但是我在这里看到这篇文章:如何克隆C# 中的通用列表?

我真的不明白扩展中发生了什么,是否可以将 shollowCopy 函数复制到扩展并避免迭代?

Is there an easier/tidier way to deep clone a list of reference types that do not implement ICloneable.

Currently have been looping through each object in the list like so:

    Dim myListCopy As New List(Of ListObj)
    For Each lo As ListObj In MyList
        myListCopy.Add(lo.ShallowCopy)
    Next

The object ListObj contains only value types and returns a shallow memberwise.

This works however I cam across this post here: How do I clone a generic list in C#?

I don't really understand whats going on in the Extension, is it possible to the shollowCopy function to an extension and avoid iteration?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

霓裳挽歌倾城醉 2024-10-01 10:45:01

如果您编写扩展方法,它仍然必须以某种方式迭代您的列表。对于 VB.net,扩展方法将类似于...

<Extension()> _
Public Function Clone(MyList as List(Of ListObj)) as List(Of ListObj)
    Dim myListCopy As New List(Of ListObj) 
    For Each lo As ListObj In MyList 
        myListCopy.Add(lo.ShallowCopy) 
    Next 
    Clone = myListCopy
End Function

然后,当您需要浅复制 ListObj 项目列表时,您将...

Dim aList As New List(Of ListObj)
''' add stuff here
Dim anotherList As List(Of ListObj)
anotherList = aList.Clone()

If you write an extension method, it will still have to iterate over your list in some way or other. For VB.net, the extension method will look something like...

<Extension()> _
Public Function Clone(MyList as List(Of ListObj)) as List(Of ListObj)
    Dim myListCopy As New List(Of ListObj) 
    For Each lo As ListObj In MyList 
        myListCopy.Add(lo.ShallowCopy) 
    Next 
    Clone = myListCopy
End Function

Then when you need to shallow copy your list of ListObj items, you would...

Dim aList As New List(Of ListObj)
''' add stuff here
Dim anotherList As List(Of ListObj)
anotherList = aList.Clone()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文