更改第二个变量时,自动更改第一个变量.如何? [英] Change first variable automatically, when second is changed. How?
问题描述
我们有诸如ref和out之类的选项.
我想做下一个:
int a = 5;
int b = a;
a = 10;
b应更改为等于10.
那么,怎么办呢?
We have such options like ref and out.
I wanna do like next:
int a = 5;
int b = a;
a = 10;
b should change to equal 10.
So, how?
推荐答案
您可以创建一个属性:
You can create a property:
int _a;
int a
{
get
{
return _a;
}
set
{
_a = value;
_b = value;
}
}
int _b;
int b
{
get
{
return _b;
}
set
{
_b = value;
}
}
这些属性应在类内部创建,但应在方法外部创建.
这是做什么的?当您想要获取a
的值时,getter将返回该字段_a
.当您想要设置a
的值时,设置器将同时更改_a
和_b
的值,并且_b
由b
的获取器返回.
在此处阅读有关属性的更多信息:
MSDN-属性(C#编程指南) [
These properties should be created inside a class, but outside a method.
What does this do? When you want to get the value of a
, the getter will return _a
, the field. When you want to set the value of a
, the setter will change the value of both _a
and _b
, and _b
is returned by the getter of b
.
Read more about properties here:
MSDN - Properties (C# Programming Guide)[^]
您可以使用指针.
You could use pointers.
static void Main(string[] args)
{
unsafe
{
int a = 5;
int* b = &a;
a = 10;
Console.WriteLine("a = {0}, b = {1}", a, *b);
Console.ReadLine();
}
}
Ref,
1)原始值的更改未反映在可变的引用类型中
Ref,
1) Original Values changes are not reflecting in reference types varaiable
这篇关于更改第二个变量时,自动更改第一个变量.如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!