簡體   English   中英

奇怪的 C# 行為

[英]Weird C# behaviour

我不知道如何描述這個問題,但我的問題是,我的函數“探路者”以某種方式改變了我的 int[,] 矩陣的數據。 有沒有辦法在不改變我的探路者功能的情況下防止這種情況發生?

我的一些代碼:

int z = 0;
AStarPathfinding = GetComponent<AStarPathfinding>();
foreach (Vector2Int target in targets)
{
    Debug.Log(matrix[0, 1].ToString() + " " + z.ToString());
    AStarPathfinding.Pathfinder(matrix, playerCords, range, target, path, targets, z);
    Debug.Log(matrix[0, 1].ToString() + " " + z.ToString());
    z++;
}

沒有

AStarPathfinding.Pathfinder(matrix, playerCords, range, target, path, targets, z);

我得到了我想要的控制台輸出:

20
20
21
21
22
22

但是有了這個功能,我得到了這個輸出:

20
20
21
41
42
42

我知道這與 c# 中函數的行為有關,但我不知道它是什么以及如何防止它。 請幫我 (;

從你得到的輸出來看AStarPathfinding.Pathfinder確實在改變矩陣。 這只是方法可以對引用類型或使用ref修飾符傳遞的值類型執行的操作。 這是因為那些參數是通過引用傳遞的,所以被調用者和調用者實際上是在處理同一個對象。 有些方法會這樣做,有些方法不會,而AStarPathfinding.Pathfinder恰好是前者之一。

聽起來你不能改變實現,所以你能做的最好的事情就是傳遞矩陣的副本。 一種方法是:

AStarPathfinding.Pathfinder((int[,])matrix.Clone(), playerCords, range, target, path, targets, z);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM