C# 将变量分配给另一个变量,并将其中的更改反映在另一个变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10604136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assign Variable to another Variable and have changes in one be mirrored in the other
提问by JMD
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.
现在 b 和 a 都会 = 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.
我问这个的原因是因为我有 4 个对象正在跟踪,并且我使用名为 currentObject 的第 5 个对象来跟踪每个对象,该对象等于用户正在使用的 4 个对象中的任何一个。但是,我只想对 currentObject 进行更改,并将其瀑布流到它来自的变量。
Thanks
谢谢
采纳答案by Jon Skeet
You need to distinguish between objects, referencesand variables. If you have two different variables (which aren't aliased via ref/out in a method, etc) then those will be independent.
您需要区分对象、引用和变量。如果您有两个不同的变量(它们不是通过方法中的 ref/out 别名等),那么它们将是独立的。
However, if two variables refer to the same object(i.e. their type is a class, and their valuesare 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 valueof 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 secondpiece 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.
编辑:我经常使用的一个类比是房子。假设我们有两张纸(变量)。两张纸上都写着相同的房子地址(这是每个变量的值,引用)。只有一间房子。如果有人用第一张纸到达房子,然后把门漆成红色,他们并没有改变他们的纸——他们改变了房子的一些东西。然后如果有人用第二张纸到达房子,他们会看到前门也是红色的。房子只有一栋,但很多纸上都写着地址。
回答by Nikhil Agrawal
With struct/value types ------- NO
使用结构/值类型 -------否
like int, boolean, double etc.
如 int、boolean、double 等。
With Reference types -------- YES
使用引用类型 --------是
like classes, objects etc.
比如类、对象等。
回答by L3tha1Am6iti0n
Here you go you can change the code in the get and set functions to do pretty much anything. You can not declare this in a function however.
在这里,您可以更改 get 和 set 函数中的代码来执行几乎任何操作。但是,您不能在函数中声明它。
int a;
int b
{
get
{
return a;
}
set
{
a = value;
}
}
回答by Samy Arous
What your are looking for is a design pattern commonly know as observer. An object B will monitor an object A (or 4 objects since this is what u need) and when A is modified, B is notified and update its state accordingly.
您正在寻找的是一种通常称为观察者的设计模式。对象 B 将监视对象 A(或 4 个对象,因为这是您需要的),并且当 A 被修改时,B 会收到通知并相应地更新其状态。
In the case of C#, I would use events. For example, define event ValueChanged on A. B would listen to this event and update its value.
在 C# 的情况下,我会使用事件。例如,在 A 上定义事件 ValueChanged。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;
}
}
回答by ironzionlion
I am not so skilled in C# programming but i've just found this quick fix: if you make an assignment in a for loop, your first variable is not modified.
我在 C# 编程方面不太熟练,但我刚刚找到了这个快速解决方案:如果您在 for 循环中进行赋值,则不会修改您的第一个变量。
int a = 3;
int b;
for (int i = 0; i < 1; i++)
{
b = a;
}
b = 2; // a = 3
Hope it helps
希望能帮助到你
回答by bigworld12
First of all you should understand what you are doing in your previous code
首先,您应该了解您在之前的代码中在做什么
- Create a 4-byte-sized variable named "a" in memory and after that give it a value of 0
- Create a 4-byte-sized variable named "b" in memory and after that give it a value of (a)'s value [Currently 0]
- Change the Value of the variable "b" to 1
- 在内存中创建一个名为“a”的 4 字节大小的变量,然后将其赋值为 0
- 在内存中创建一个名为“b”的 4 字节大小的变量,然后给它一个值(a)的值 [当前为 0]
- 将变量“b”的值更改为 1
But this isn't what you want, what you want is something more like this
但这不是你想要的,你想要的是更像这样的东西
- Create a 4-byte-sized variable named "a" in memory and after that give it a value of 0
- Create a 4-byte-sized variable named "b" in memory and after that change the address of the variable "b" so that it doesn't refer to these 4 bytes anymore,but instead refer to (a)'s 4 bytes
- 在内存中创建一个名为“a”的 4 字节大小的变量,然后将其赋值为 0
- 在内存中创建一个名为“b”的 4 字节大小的变量,然后更改变量“b”的地址,使其不再引用这 4 个字节,而是引用 (a) 的 4 个字节
What you are asking for is both Bad + Impossible
你要的是坏的+不可能的
- Bad : you have just created an empty space of 4 bytes that have no use at all and completely ignored them
- Impossible : Because you can't change the address of a value type (thus they are called "value" types not "reference" types)
- 不好:您刚刚创建了一个完全没有用的 4 个字节的空白空间并完全忽略了它们
- 不可能:因为您无法更改值类型的地址(因此它们被称为“值”类型而不是“引用”类型)
But what you "Should" be asking for is this
但是你“应该”要求的是这个
- Create a 4-byte-sized variable named "a" in memory and after that give it a value of 0
- Create an address that refers to the variable a
- Change the value of a through this address
- 在内存中创建一个名为“a”的 4 字节大小的变量,然后将其赋值为 0
- 创建一个引用变量 a 的地址
- 通过这个地址改变a的值
And this approach is actually totally OK, and it uses Pointers, Pointers simply are addresses in memory.
这种方法实际上完全可以,它使用Pointers, Pointers 只是内存中的地址。
Note : To use pointers you have to Allow unsafe code in Project > Build
注意:要使用指针,您必须在 Project > Build 中允许不安全代码
In code here is how to do it :
在代码中是如何做到这一点的:
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 to 1
//now a = 1
}

