【问题标题】:Can you change the values of a class by passing it in?你能通过传入一个类来改变它的值吗?
【发布时间】:2013-11-10 19:31:52
【问题描述】:

我已经为此搜索了 Stack Overflow,但我找到了一个答案相互矛盾的答案,但没有任何答案是直截了当的。

这是在 Microsoft XNA 中。 Vector2 是一个可以容纳 X 和 Y 的类。 该函数正在查看其尊重方向的正方形是否为空。如果是,请朝相应的方向移动。 NORTH 函数将位置的 y 值减 1。它将 2 添加到矢量,但它不会转移到屏幕本身并移动该块。问题是我不能像这样编辑向量的值,我需要返回它并设置它吗?

public static Boolean domove(Vector2 location, int[,] board, char dir) //won't work, I cant edit it's values like this.
{
    if (dir == 'N')
    {
        if (board[(int)location.X, (int)location.Y - 1] == 1) { NORTH(location); Console.WriteLine(location); return true; } //if the square ahead, which would be a potential wall, is 0, or unoccupied, hop forward 2. go into technicalities of another player there later.
    }
    else if (dir == 'S')
    {
        if (board[(int)location.X, (int)location.Y + 1] == 1) { SOUTH(location);  return true; } //if the square ahead, which would be a potential wall, is 0, or unoccupied, hop forward 2. go into technicalities of another player there later.
    }
    else if (dir == 'W')
    {
        if (board[(int)location.X - 1, (int)location.Y] == 1) { WEST(location); return true; } //if the square ahead, which would be a potential wall, is 0, or unoccupied, hop forward 2. go into technicalities of another player there later.
    }
    else if (dir == 'E')
    {
        if (board[(int)location.X + 1, (int)location.Y] == 1) { EAST(location); return true; } //if the square ahead, which would be a potential wall, is 0, or unoccupied, hop forward 2. go into technicalities of another player there later.
    }
    return false;
}

【问题讨论】:

  • Vector2 是一个结构体,因此按值传递,而不是按引用传递。一旦方法结束,对传递给方法的任何更改都会丢失。而是通过引用传递位置。
  • @S_F: Everything 如果参数不是refout,则按值传递。

标签: c# class xna pass-by-reference


【解决方案1】:

您必须通过引用传递值才能在其上写入而无需再次返回。请参阅有关 ref 关键字的 C# 参考文档: http://msdn.microsoft.com/en-us/library/14akc2c7.aspx

【讨论】:

    猜你喜欢
    • 2023-04-11
    • 2010-12-29
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    相关资源
    最近更新 更多