如何解决如何从一个方法返回多个值?
从以下代码中,我希望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);
}
,
您可以通过数组或集合来实现。
-
使用数组
int[] result = new int[numberofDraws]; result[j] = your result (1,2,3 based on condition) return result;
-
使用列表
List<int> result = new List<int>(); result.Add(1); return result;
注意::如果要使用数组使用int[]
,请根据使用情况更改返回类型;如果要使用列表使用List<int>
,则可以使用返回类型。
您可以使用 out 参数或 元组 从任何函数返回多个值,并进行检查。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。