加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在其他类中分配值?

发布时间:2020-12-16 02:01:25 所属栏目:百科 来源:网络整理
导读:我想创建一个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. }}
我想创建一个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();
    }
}

这是我的问题.有没有人知道如何解决它?我会很感激的.

解决方法

Point是一个结构(即值类型).您通过引用传递它,但是然后通过将其指定给点域来在PointMover的构造函数中创建点实例的副本:

public void Set(ref Point p)
{
    point = p; // here you create copy of passed 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)方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读