【问题标题】:How to assign a value in other classes?如何在其他类中赋值?
【发布时间】:2014-04-28 13:50:15
【问题描述】:

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

和我的主要课程:

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();
    }
}

这是我的问题。有谁知道如何解决它?我会很感激的。

【问题讨论】:

  • Pointclass 还是 struct
  • @DStanley Point 是一个结构体。
  • 这无法完成。您必须将Point 包装在一个类中。你可以使用不安全的代码,但我建议不要这样做,我认为这会给你带来比它解决的问题更多的问题。
  • @LasseV.Karlsen 是的,我创建了一个 MyPoint 类来替换 struct Point 并且它可以工作。非常感谢!

标签: c# assign


【解决方案1】:

Point 是一个结构体(即值类型)。您通过引用传递它,但随后通过将其分配给point 字段,在PointMover 的构造函数中创建点实例的副本:

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)方法。

【讨论】:

  • 谢谢!这两种方法都很好。但在我的情况下,我需要通过 Point 一次,Mover 类会自动移动点几次以生成平移动画。所以看来我必须选择第一个使用类来替换结构的方法。
猜你喜欢
  • 2012-02-02
  • 2020-06-20
  • 1970-01-01
  • 1970-01-01
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-08
相关资源
最近更新 更多