c# - 如何在其他类中赋值?

标签 c# assign

我想创建一个 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/

相关文章:

c# - 在真实场景中实现身份服务器身份验证

c# - 如何在Windows Server 2012 R2上远程连接MongoDB

c# - 使用BackGroundWorker的错误处理条件失败

c# - 数据格式问题。将 GridView 导出到 Excel

c++ - 自己的 vector 分配实现

c# - C# Xml 反序列化中的问题

python - Pandas 将新列名分配为字符串

c - 这个 char* 赋值发生了什么? (混合类型的逗号运算符)

C++ 将数组分配给彼此; type int* = type int 有效但 int = int*?

ios - Xcode 中用于检查功能是否保留的工具?