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

标签 c# return

在以下代码中,我希望 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/

相关文章:

c# - 递归和 await/async 关键字

c# - ListView 可见属性

c# - Caliburn Micro - 从模型类的 ItemSource 绑定(bind)自动创建 ViewModel 对象?

haskell - do block 中的返回类型

c++ - 我可以在非 void 返回函数上使用 [[noreturn]] 吗?

c# - 可以从字符串或内存流加载 App.Config 吗?

c# - 窗口关闭时正在运行的任务会发生什么情况?

Javascript - 接受参数并返回包含 "x"的字符串的函数

java - 缺少返回声明

c++ - 声明的允许使用上下文