2

Is it possible to have some variable shared between some objects of the same class such that, when the value is changed in one object, it will also change in the other object? Static variables would not work in this case, because there could be 2 objects that all have some related variable and another 2 objects that have a different related variable.

For example, say I have 4 squares that are arranged to make one large square, and the squares coordinates lie in an x,y,z plane. When the 4 squares are together, they would all have a point that lies in the center of the biggest square.

Pretend this square also has a z coordinate. Now, the squares will all share the point that lies in the center. The top left square's bottom right corner, the top right square's bottom left corner, etc., will all have the same (x, y, z) value.

Now what I want, is such that if the z value of one square changes, they will all change without any extra code, like they all point to the same memory location, so they "automatically" update in a sense.

Is something like this possible?

4

3 回答 3

4

Here is one way you could do this. Each square's data property is pointing to the same reference.

class Square 
{
     private SharedData Data;

     public Square(SharedData data)
     {
        this.Data = data;
     }
}

class SharedData
{
     public double Z { get; set; }
}

SharedData data = new SharedData() { Z = 100.0 }

Square topLeft = new Square(data);
Square topRight = new Square(data);
Square bottomLeft = new Square(data);
Square bottomRight = new Square(data);

You can put SharedData behind an interface that provides read-only access to the squares if you wish. If the squares are not supposed to modify the value of Z this would be a safer approach.

interface IReadOnlyData
{
    double GetZ();
}

class SharedData : IReadOnlyData
{
     public double Z { get; set; }
     IReadOnlyData.GetZ() { return Z; }
}

class Square
{
    private IReadOnlyData Data;

    public Square(IReadOnlyData data)
    {
        this.Data = data;
    }
}
于 2013-04-12T04:18:58.303 回答
3

I think you are thinking about this the wrong way. If all of the squares are to be treated as logically one object, make one object that encapsulates all of them and provides the logic you want. You shouldn't have objects sneakily mutating other objects' values behind their backs, IMO.

于 2013-04-12T03:48:19.903 回答
1

Implement the observable pattern.

Check this post: Super-simple example of C# observer/observable with delegates

Hope it helps you.

于 2013-04-12T12:25:19.167 回答