按值实例化局部变量?

发布于 2024-08-17 05:10:55 字数 529 浏览 13 评论 0原文

我有点理解为什么会发生这种情况,但不完全理解。我有一个带有 Shared (Static) 变量的基类,声明如下:

Public Shared myVar As New MyObject(arg1, arg2)

在派生类的方法中,我设置了一个局部变量,如下所示:

Dim myLocalVar As MyObject = myVar

现在,当我执行类似 myLocalVar.Property1 += value 的操作,Property1 中的值将保留到该方法的下一次调用!我想我明白为什么会发生这种事; myVar 是通过引用而不是值设置的,但我以前从未遇到过类似的情况。有没有什么方法(除了我的解决方法,即使用 myVar 的属性值创建一个新对象)来创建 myLocalVar 按值

I sort of understand why this is happening, but not entirely. I have a base class with a Shared (Static) variable, declared like so:

Public Shared myVar As New MyObject(arg1, arg2)

In a method of a derived class, I set a local variable like so:

Dim myLocalVar As MyObject = myVar

Now when I do something like myLocalVar.Property1 += value, the value in Property1 persists to the next call of that method! I suppose I get why it would be happening; myVar is being set by reference instead of by value, but I've never encountered anything like this before. Is there any way (other than my workaround which is to just create a new object using the property values of myVar) to create myLocalVar by value?

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

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

发布评论

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

评论(1

红玫瑰 2024-08-24 05:10:55

当您创建 myLocalVar 时,您正在创建对同一共享对象的新引用。如果您确实想要共享实例的本地副本,则需要创建一个真实副本。

这是通过克隆实例或使用允许您创建实例副本的类型的复制构造函数来完成的。然而,这并不像听起来那么简单,由于深复制和浅复制之间的差异,如果您正在访问的属性只是对同一实例的浅复制引用,则克隆或复制的实例可能会给您带来类似的问题。原始实例上的属性正在引用。

在这种情况下,我要做的最好的事情是仅创建您需要的共享实例部分的本地副本,而不是复制整个对象图。这意味着创建 Property1 类型的本地副本并使用它。

When you create myLocalVar you are creating a new reference to the same shared object. If you truly want a local copy of the shared instance you will need to create a true copy.

This is done by either cloning the instance or with a copy constructor on the type that allows you to create a copy of the instance. This is not as simple as it sounds, however, due to the differences between deep and shallow copying and a cloned or copied instance could create similar problems for you if the property you are accessing is simply a shallow-copied reference to the same instance that the property on the original instance is referencing.

The best thing I to do in this case is to create a local copy of only the parts of the shared instance that you need, rather than copying the entire object graph. This means create a local copy of whatever type Property1 is and using that.

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