【发布时间】:2023-01-11 03:45:26
【问题描述】:
我对编程很陌生,我正在尝试将随机机器人移动添加到我制作的小游戏中。我的想法是制作一个包含所有合法移动的元组列表,然后从该列表中随机选择一个元组,然后解构并更改二维数组中的值。 我在整个互联网上都看过并找到了一种制作元组列表的方法(我认为),但无法从该列表中随机选择一个元素。
这是我试过的:
List<Tuple<int, int>> legalMoves; // To make the list of tuples
// Later on in a double for-loop that iterates through all the rows and columns of the 2D-array I check if that certain row and column combination is a legal move and then add it to the list like so:
legalMoves.Add(Tuple.Create(row, col));
//Then in a different method I try to pick a random element from that list (this doesn't work)
Random random = new Random();
int randomIndex = random.Next(legalMoves.Count);
(int, int) randomMove = legalMoves[randomIndex];
它在最后一行给出了以下错误: 错误 CS0029 无法将类型“System.Tuple<int, int>”隐式转换为“(int, int)”
有什么办法可以使这项工作?
提前致谢!
【问题讨论】:
-
正确的类型是 ValueTuple,而不是 Tuple
-
如果有疑问,声明为
var randomMove = legalMoves[randomIndex];,看看推断出什么Type