集合中的结构

发布于 2024-12-13 02:14:22 字数 541 浏览 3 评论 0原文

我想存储对集合中一堆结构的引用。一般的脚手架看起来像这样:

Structure myStructType
  Dim prop1 as String
  Dim prop2 as int
End Structure


Dim myList as new List(Of myStructType)()

'Wrongness below
Dim myStruct as new myStructType()
myStruct.prop1 = "struct1"
myStruct.prop2 = 1
myList.Add(myStruct)

myStruct = new myStructType()
mystruct.prop1 = "number two"
mystruct.prop2 = 2
myList.Add(myStruct)

现在这不起作用,因为它引用相同的内存。我真正想要的是“按值传递引用”行为,该行为也用于引用类型,以便我可以轻松地继续生成更多引用类型。

除了将结构体变成类之外,还有什么方法可以解决这个问题吗?这实际上是使用结构的正确方法,还是我完全错了?

I would like to store references to a bunch of structs in a collection. The general scaffolding looks like this:

Structure myStructType
  Dim prop1 as String
  Dim prop2 as int
End Structure


Dim myList as new List(Of myStructType)()

'Wrongness below
Dim myStruct as new myStructType()
myStruct.prop1 = "struct1"
myStruct.prop2 = 1
myList.Add(myStruct)

myStruct = new myStructType()
mystruct.prop1 = "number two"
mystruct.prop2 = 2
myList.Add(myStruct)

now this doesn't work, because it's referencing the same memory. What I would really want is the 'pass reference by value' behaviour that is also used for reference types, so that I can easily keep producing more of them.

Is there any way to fix this other than to make the structs into classes? Is this actually a proper way to use structs, or do I have it all wrong?

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

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

发布评论

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

评论(1

最美的太阳 2024-12-20 02:14:23

无论它是结构体还是类,此代码都会执行相同的操作,因为您正在为每个对象调用 new myStructType() 。话虽如此,请注意稍后检索和修改这些 myStructType 对象的行为会有所不同。如果它是从结构派生的,那么您将在检索时复制数据,而使列表中的原始数据保持不变。如果它是从类派生的,那么您将获得对该对象的引用,并且使用该引用所做的更改会更改列表中的实例。

我仍然想知道您试图通过使用结构而不是类来完成(或避免)什么?

This code does the same thing whether it is a struct or a class because you are invoking new myStructType() for each object. That being said, be aware that later retrieving and modifiying those myStructType objects behave differently. If it is derrived froma structure then you are copying the data on a retrieve, leaving the original untouched in the list. If it is derrived from a class then you are getting a reference to that object and changes made using that reference change the instance in the list.

I still wonder what you are trying to accomplish (or avoid) by using structures instead of classes?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文