gpt4 book ai didi

c# - 如何从一个方法返回多个值?

转载 作者:行者123 更新时间:2023-12-02 02:41:58 28 4
gpt4 key购买 nike

在以下代码中,我希望 y 返回多个值,但程序仅返回最后一个值。

public int runDraw()
{
for (int j = 1; j <= numberofDraws; j++)
{
...
if (even_count > odd_count)
{
Console.WriteLine("The result of {0} draw is Even.", j);
y = 1;
}
else if (even_count < odd_count)
{
Console.WriteLine("The result of {0} draw is Odd.", j);
y = 2;
}
else
{
Console.WriteLine("The result of {0} draw is Draw.", j);
y = 3;
}
}
return y;
}

最佳答案

一种选择是返回 int 枚举,因为单个 int 不能直接表示多个值。这是一个使用 yield return 的示例,如果您需要的话,它只会继续到下一个值。

    public IEnumerable<int> runDraw()
{
for (int j = 1; j <= numberofDraws; j++)
{
...
if (even_count > odd_count)
{
Console.WriteLine("The result of {0} draw is Even.", j);
yield return 1;
}
else if (even_count < odd_count)
{
Console.WriteLine("The result of {0} draw is Odd.", j);
yield return 2;
}
else
{
Console.WriteLine("The result of {0} draw is Draw.", j);
yield return 3;
}
}
yield return y;
// What you do here really depends on your unshared logic
// You might return 0 or throw an exception if this is invalid
}

然后您可以迭代地访问这些值,例如使用 foreach 循环:

foreach (int j in runDraw())
{
Console.WriteLine(j);
}

关于c# - 如何从一个方法返回多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63440254/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com