在方法中忽略变量加法

时间:2015-12-02 22:17:04

标签: c# function procedures

前提是根据他们选择的方向和骰子卷的价值在网格周围移动角色。

CalculateMove内调用函数PrepareMove。在CalculateMove中,变量finishXfinishYdiceValue的值加或减。

即使在if语句之外写入+ = 3,也会忽略CalculateMove中与finalX或finalY有关的所有内容。 The screenshot of a little debug log shows that the variables finishX, finishY and foo are not being treated in the method.

static void PrepareMove(Position startPosition, Position finishPosition, Player playerGreen, Player playerYellow, Player playerBlue, Player playerRed, string playerMoveDirection, string currentPlayer, string winningPlayer, string[,] board, int diceValue, int startX, int startY, int finishX, int finishY, bool gameOver)
    {            
        GetStartPosition(board, startPosition, currentPlayer, startX, startY);            
        CalculateMove(playerMoveDirection, board, diceValue, startX, startY, finishX, finishY);
        Console.WriteLine("\nStart XY = " + startX + "-" + startY + "\nDice Value = " + diceValue + "\nMoveDir = " + playerMoveDirection + "\nFinish XY = " + finishX + " -- " + finishY + "\n"); 
        CheckPieceCaptured(board, playerGreen, playerYellow, playerBlue, playerRed, currentPlayer, winningPlayer, finishX, finishY, gameOver); 
        MakeMove(board, startX, startY, finishX, finishY); 
    }

    static void CalculateMove(string playerMoveDirection, string[,] board, int diceValue, int startX, int startY, int finishX, int finishY)
    {
        finishX += 3; 
        if (playerMoveDirection.ToUpper().Equals("UP"))
        {
            finishX = startX;
            finishY = startY - diceValue;
        }
        else if (playerMoveDirection.ToUpper().Equals("DOWN"))
        {
            finishX = startX;
            finishY = startY + diceValue;
        }
        else if (playerMoveDirection.ToUpper().Equals("LEFT"))
        {
            finishX = startX - diceValue;
            finishY = startY;
        }
        else if (playerMoveDirection.ToUpper().Equals("RIGHT"))
        {
            finishX = startX + diceValue;
            finishY = startY; 
        }
    }

任何想法的家伙? :( 谢谢,

2 个答案:

答案 0 :(得分:2)

您按值传递finishXfinishY,因此当您在CalculateMove方法中更改其值时,您将更改本地副本的值{{1方法,而不是原始变量。

您需要通过引用传递CalculateMovefinishX,如下所示:

finishY

您还需要为static void CalculateMove( string playerMoveDirection, string[,] board, int diceValue, int startX, int startY, ref int finishX, ref int finishY) { ... } 方法执行相同的操作。

顺便说一下,如果你创建一个类来保存你的X和Y值会更好:

PrepareMove

然后对方法进行如下定义:

public class Coordinates
{
    public int X {get;set;}
    public int Y {get;set;}
}

然后你可以像这样访问坐标:

static void CalculateMove(
    string playerMoveDirection,
    string[,] board,
    int diceValue,
    Coordinates start_coordinates,
    Coordinates finish_coordinates)
{
    ...
}

这将使您的代码更具可读性,您不必通过引用传递它。

对于其他方法,您也应该这样做。

答案 1 :(得分:2)

你需要使用" ref int finishX"和" ref int finishY"在函数退出后,让参数保留值。

https://msdn.microsoft.com/en-us/library/14akc2c7.aspx