我想创建一个 aminator 类。但不能修改其他类中的字段值。
这是我简化的动画师类:
public class PointMover
{
Point point;
public void Set(ref Point p)
{
point = p;
}
public void Move(int dX)
{
point.X += dX; // The point.X is modified here.
}
}
和我的主要类(class):
public partial class Form1 : Form
{
PointMover pointMover = new PointMover();
Point point = new Point(0, 0);
private void Form1_Load(object sender, EventArgs e)
{
pointMover.Set(ref point);
pointMover.Move(10); // But point.X is NOT modified here.
this.Close();
}
}
这是我的问题。有没有人知道如何解决它?我将不胜感激。
最佳答案
Point
是一个结构(即值类型)。您通过引用传递它,但是您随后通过将其分配给 point
字段在 PointMover
的构造函数中创建 point 实例的副本:
public void Set(ref Point p)
{
point = p; // here you create copy of passed point
}
因此 point
的修改不会影响 p
(因为它们代表不同的结构实例)。
注意:如果 Point
是一个引用类型(即类),那么这个赋值将复制一个引用,并且两个变量将引用堆中的同一个实例。
为了修复此行为,您需要修改通过引用传递的点而不创建副本。例如
public static void Move(ref Point point, int dX)
{
point.X += dX;
}
用法:
PointMover.Move(ref point, 20);
或者您可以简单地使用 Point.Offset(int dx, int dy)
方法。
关于c# - 如何在其他类中赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23342919/