我对值类型作为类中的属性的概念有点困惑。 据我了解,当调用 getter 时 - 返回值类型的副本。 举个例子吧:
public struct Point
{
public int X;
public int Y;
public void Set(int x, int y)
{
X = x;
Y = y;
}
}
public class Test
{
public Int32 X { get; set; }
public void SetX(int x) => X = x;
public Point Point { get; set; }
}
static void Main(string[] args)
{
var test = new Test();
test.SetX(10);
test.Point.Set(20, 30);
Console.WriteLine(test.X);
Console.WriteLine($"{test.Point.X} {test.Point.Y}");
}
Point 没有被修改,因为它是一个值类型,而 getter 给了我们一个副本,这是有道理的。我不明白的是 - 为什么在这种情况下 X 被修改?它也是一种值类型。这对我来说似乎是矛盾的。 请帮助我了解我所缺少的东西
Point 没有被修改,因为它是值类型,而 getter 给了我们一个副本,这是有道理的
是的,因为您可以对自动属性
getter返回的
Point
的本地副本进行更改。
我不明白的事情 - 为什么在这种情况下 X 被修改?
因为您正在修改包含
X
的对象,而不是 X
的副本。 X = x
调用setter(这里没有发生“返回副本”)作为自动属性,它将相应的值写入相应的内存位置。
模拟此行为的代码
Point
可以如下所示:
public void SetPoint(int x, int y) => Point = new Point{X= x, Y =y};
在这两种情况下,以下内容都有效:
test.X = 42;
test.Point = new Point {X = 7, Y = 42}
要修改“Test.Point”代码:
static void Main(string[] args)
{
var test = new Test();
test.SetX(10); // you assign a new value to the property
// test.Point.Set(20, 30); - you change a copy of the value without assignment of the result to the property
test.Point = (new Point()).Set(20, 30); // or ... = new Point(){ X = 20, Y = 30 }
Console.WriteLine(test.X);
Console.WriteLine($"{test.Point.X} {test.Point.Y}");
}