【问题标题】:Choosing a random element from a list of tuples C#从元组列表中选择一个随机元素 C#
【发布时间】: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

标签: c# winforms random tuples


【解决方案1】:

语法 (int, int) 定义的是 ValueTuple&lt;int,int&gt; 而不是 Tuple&lt;int,int&gt;。将列表定义更改为:

List<ValueTuple<int, int>> legalMoves;

Tuple.CreateValueTuple.Create

【讨论】:

    猜你喜欢
    • 2013-10-19
    • 1970-01-01
    • 2011-05-29
    • 2014-07-23
    • 2014-02-07
    • 1970-01-01
    • 2017-04-26
    相关资源
    最近更新 更多