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

C# 如何从一个方法返回多个值?,c#,return,C#,Return,在下面的代码中,我希望y返回多个值,但程序只返回最后一个值 public int runDraw() { 对于(int j=1;j奇数_计数) { WriteLine({0}draw的结果是偶数。”,j); y=1; } else if(偶数计数

在下面的代码中,我希望
y
返回多个值,但程序只返回最后一个值

public int runDraw()
{
对于(int j=1;j奇数_计数)
{
WriteLine({0}draw的结果是偶数。”,j);
y=1;
}
else if(偶数计数<奇数计数)
{
WriteLine({0}draw的结果是奇数的。”,j);
y=2;
}
其他的
{
WriteLine(“0}draw的结果是draw.”,j);
y=3;
}
}
返回y;
}

一个选项是返回int的枚举,因为单个int不能直接表示多个值。下面是一个使用
收益率返回的示例,如果您要求下一个值,它只会麻烦您继续下一个值

    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
    }

您可以通过数组或集合来实现这一点

  • 使用数组

     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;
    
    列表结果=新列表();
    结果.增加(1);
    返回结果;
    

  • 注意:如果使用数组,请根据用法更改返回类型使用
    int[]
    ,如果使用列表使用
    list
    可以使用out参数或元组从任何函数返回多个值,检查它们。

    您希望该方法返回什么类型的对象?
    y
    一次只能保存一个值。在循环中重置它的事实并不会改变这一点,它只会在整个循环运行后返回
    s。您可以使用迭代器方法。
     List<int> result = new List<int>();
     result.Add(1);
     return result;