Exchange links between objects

I want several objects to exchange a link through a private field, so that any of the objects can assign this field, and the updated field will be visible to other objects using this link. I originally hoped to do this:

class SomeObject
{
    private ref DataObject _data;
    public SomeObject(ref DataObject data)
    {
         _data = ref data; // or something similar
    }

    public ChangeData(DataObject newData)
    {
         _data = data;
         // at this point, *other* SomeObject instances that were
         // created with the same reference should also have _data == newData
    }
}

But, of course, you cannot use it refas follows: it is refintended only for method parameters. And the static field will not work, since not all instances SomeObjectshould refer to the same object --- rather, the object in question must be set in the constructor.

Obviously, I could solve this by simply adding a simple wrapper class. But is there a better way? Is there any class SharedReference<T>I can use?

, , . , _data DataObject. . , , , , . , _data _data .

+3
4

, , SharedReference<T>.

- :

public sealed class SharedReference<T>
    where T : class
{
    public T Reference
    {
        get; set;
    }
}
+4

ref, . ref ( ), , null - , .

: , , . -, , , , , , , .

Singleton - , , Singleton, , , - . , .

, , .

+1

:

class SomeObject
{
    // you probably want to make this readonly
    private readonly DataObject[] _data;     

    public SomeObject(DataObject[] data)
    {
         _data = data;
    }

    public void ChangeData(DataObject newData)
    {
        _data[0] = o;
    }

    // and you could define your own accessor property...
    private DataObject Data
    {
        get { return _data[0]; }
        set { _data[0] = value; }
    }
}

, , ""

+1

#,


class SomeObject
{
    private DataObject _data;
    public SomeObject(DataObject data)
    {
         _data = data;
    }
}

, , DataObject , .

>

, , .
.

0
source

Source: https://habr.com/ru/post/1753730/


All Articles