C # Updating object objects without interrupting an instance

I want to update the instance with the properties of the newly created object at the same time, but not break the binding of the instance to other variables. For instance,

public class MyClass{
   public double X;
   public double Y;
}

MyClass a = new MyClass(2,1);
MyClass b = a;

MyClass c = new MyClass(1,1);

a = c; //'b' should also be equal to 'a'.
//I dont want to do something like this:
a.Y = c.Y;
a.X = c.X;

In my code, “b” is actually unavailable because it is tied to some user interface, “a” is my only way to update “b”. Therefore, after the call to 'a = c' b should take place [1,1].

+3
source share
3 answers

Experimental: please feel free to "blow it out of the water" :) Tested in VS 2010 beta 2 against FrameWork 4.0 and 3.5 (full, not "client" versions).

private class indirectReference
{
    // using internal so Loc is not visible outside the class
    internal struct Loc
    {
        public double X;
        public double Y;
    }

    // publicly exposed access to the internal struct
    public Loc pairODoubles;

    // ctor
    public indirectReference(double x, double y)
    {
        pairODoubles.X = x;
        pairODoubles.Y = y;
    }
}

// test ...

indirectReference r1 = new indirectReference(33, 33);

indirectReference r2 = r1;

indirectReference r3 = new indirectReference(66, 66);

// in this case the doubles in r2 are updated 
r1.pairODoubles = r3.pairODoubles;
0
source

You can do something like this:

class Wrapper
{
    public Wrapper(Location l)
    {
        this.L = l;
    }
    public Location L;
}

Wrapper a = new Wrapper(new Location(2,1));
Wrapper b = a;
Location c = new Location(1,1);
a.L = c;

, . .

+1

Don't you think that an MyClass immutable approach would be a suitable approach?

Or: you must do reference counting through the shell.

0
source

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


All Articles