如何在两个对象之间共享对象 [英] How do I share an object between 2 objects

查看:97
本文介绍了如何在两个对象之间共享对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我想弄清楚如何在其他2个对象中共享同一个对象。

所以让''为了简单起见,我称之为A级和B级。



B级有A级副本。



从B类创建对象X和Y并从A类创建对象Z



我希望对象X和Y对对象具有相同的引用Z,当任一个对象修改Z时,它们都有更新的副本。



我知道如果我使用静态变量这可以简化但是适用于该类的所有对象。我只想让变量在一些对象之间共享而不是整个系列。



提前谢谢。

Hi,

I am trying to figure out how to share the same object among 2 other objects.
So let''s call it class A and B for simplicity sake.

Class B has a copy of class A in it.

Creating object X and Y from class B and creating object Z from class A.

I want both object X and Y to have the same reference to object Z and when either objects modify Z, both of them have the updated copy.

I know this can be simplified if I were to use a static variable but that applies to all objects of the class. I just want the variable to be shared among some of the objects rather than the whole series.

Thanks in advance.

推荐答案

你迷失了,需要从一开始就走。



Class是一种类型。您无法复制类型。您可以复制对象,类型的实例。类是引用类型。当你创建一个类型的实例时,你也会得到相同对象的引用。

You are lost very well, need to go from the very beginning.

Class is a type. You cannot copy a type. You can copy an object, instance of a type. Classes are reference types. When you create, say, an instance of a type, your get too references of the same objects.
class A { /* ... */ }

A a = new A();
A b = a;
// at this point, a and b are different references to the same object



引用本身也是一个对象,因此引用类型的对象本身就是引用,可以将其视为一个对象,引用引用的对象。这样, a.SomeMember = 3 将使 b.SameMember 也是3.同时,如果以后你写 b = new A(); ,你将失去对与 a 并有两个不同的对象,由两个引用引用。换句话说,对参考 b 的新分配不会影响 a



现在,假设两个不同的对象具有 A 类型的字段。将一个复制到另一个时,它们将引用同一个对象。此对象将在此另一个类或结构的两个实例之间共享。或者他们可以引用 A 的不同对象。



这是你所有非常非常基础的东西应该清楚地了解100%。没有它,根本就没有.NET编程。这就是你没有开始阅读OOP的地方......



-SA


The reference itself is also an object, so an object of a reference type is a reference itself, which can be considered as a an object, and the object referenced by a reference. This way, a.SomeMember = 3 will make b.SameMember also 3. At the same time, if later you write b = new A();, you will loose an extra reference to the same object as the one referenced by a and have two different objects, referenced by two references. In other words, new assignment to the reference b will not affect a.

Now, imagine that two different objects have fields of the type A. When you copy one to another, they will reference the same object. This object will be shared between two instanced of this other class or structure. Or they can reference distinct, different object of A.

This is all the very, very basics which you should understand 100% clearly. Without it, there is no .NET programming at all. And this is the point where you did not start "read" OOP yet…

—SA


这篇关于如何在两个对象之间共享对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆