Assign a variable to another variable and change it to another.

Is it possible to assign a variable to another variable, and when you change the second variable, the variables are waterfalls before the first variable?

Like this.

int a = 0;
int b = a;
b = 1;

now both b and a will = 1.

The reason I ask about this is because I have 4 objects that I am tracking, and I am tracking each using the 5th object called currentObject, which is equal to any of the four objects that the user uses. However, I would just like to make changes to currentObject and just have a waterfall for the variable from which it came.

thank

+3
source share
6 answers

, . ( ref/out ..), .

, (.. - , ), . , , . :

public class SomeMutableClass
{
    public string Name { get; set; }
}

// Two independent variables which have the same value
SomeMutableClass x1 = new SomeMutableClass();
SomeMutableClass x2 = x1;

// This doesn't change the value of x1; it changes the
// Name property of the object that x1 value refers to
x1.Name = "Fred";
// The change is visible *via* x2 value.
Console.WriteLine(x2.Name); // Fred

, , .

EDIT: , , - . , (). ( , ). . - , , , - - . , - , , , . , , .

+13

struct/value ------- NO

int, boolean, double ..

--------

, ..

+3

, ,

  • 4 "a" 0
  • 4 "b" (a) [ 0]
  • "b" 1

, , , , .

  • 4 "a" 0
  • 4 "b" "b", 4 , (a) 4

, , - Bad + Impossible

  • : 4 , .
  • : ( , "", "" )

, "",

  • 4 "a" 0
  • , a
  • a

, , .

. , Project > Build

:

int a = 5;
unsafe //use unsafe around the areas where pointers exist
{
    int* b = &a; //create an address named b that refers to a
    *b = 1; //change the value of the variable that exists at the address b refers to to 1

    //now a = 1
}
+1

, , - , . B A ( 4 , , ), A , B .

# . , ValueChanged A. B .

public delegate void ChangedEventHandler(object sender, EventArgs e);

Class A
{
   public event ChangedEventHandler Changed;
   int val = 0;
   int Val
   {
      get { return val;}
      set { 
          if ( val != value ) val = value
          {
              val = value;
              if (Changed != null) Changed(this, new EventArgs());
          }

   }
}


class B
{
    A obj1, obj2, obj3, obj4;
    int Val {get;set;}
    A CurrentlyWatched {get;set;}

    public B()
    {
       obj1 = new A();
       obj1.Changed += new ChangedEventHandler(ElementChanged);
       obj2 = new A(); 
       ...
    }

    private void ElementChanged(object sender, EventArgs e) 
      {
         this.CurrentlyWatched = sender as A;
         this.Val = CurrentlyWatched.Val;
      }
}
0

get set, . .

    int a;
    int b
    {
        get
        {
            return a;
        }
        set
        {
            a = value;
        }
    }
-1

#, : for, .

int a = 3;
int b;

for (int i = 0; i < 1; i++)
{
   b = a;
}

b = 2; // a = 3

,

-3

All Articles