Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

c# - Assign Variable to another Variable and have changes in one be mirrored in the other

Is it possible to assign a variable to another variable and when you change the second variable the change waterfalls down to the first variable?

Like this.

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

now both b and a would = 1.

The reason I ask this is because I have 4 objects I'm keeping track of, and I keep track of each using a 5th object called currentObject that equals whichever of the 4 objects the user is using. However, I would like to just make a change to the currentObject and just have it waterfall to the variable it came from.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to distinguish between objects, references and variables. If you have two different variables (which aren't aliased via ref/out in a method, etc) then those will be independent.

However, if two variables refer to the same object (i.e. their type is a class, and their values are equal references), then any changes to that object will be visible via either variable. It sounds like this is what you want to achieve. For example:

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's value refers to
x1.Name = "Fred";
// The change is visible *via* x2's value.
Console.WriteLine(x2.Name); // Fred

If you're not entirely comfortable with how reference types and objects work, you may wish to read my article about them.

EDIT: One analogy I often use is of a house. Suppose we have two pieces of paper (variables). The same house address is written on both pieces of paper (that's the value of each variable, the reference). There's only one house. If someone uses the first piece of paper to get to the house, then paints the door red, they're not changing anything about their piece of paper - they're changing something about the house. Then if someone uses the second piece of paper to get to the house, they'll see the front door is red too. There's only one house, however many pieces of paper have its address written on them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...