c# - 你如何在 C#/csharp 中返回 2 个变量?

标签 c# arrays variables methods tuples

<分区>

引用方法WutHap(抱歉,我没写注释),我需要同时返回int agg和int sub来获取方法NumGen 将在 Main 中有 int agg 和 sub。我知道你可以使用数组和元组,但我做起来有困难。如果您需要更多上下文,请询问需要澄清的内容。我很愚蠢,所以说它需要更多的上下文可能不会导致实际的澄清。是的,我知道代码很糟糕,但这不是重点。

class Program
    {
        static void Main(string[] args)
        {
            int agg = 50;
            int sub = 50;
            for (int i = 0; i < 100; i++)
            {
                WutHap(agg, sub);
            }
            int pop = sub + agg;
            Console.WriteLine("Total aggs = " + agg);
            Console.WriteLine("Total subs = " + sub);
            Console.WriteLine("Total population = " + pop);
            Console.ReadKey();
        }
        static string NumGen()
        {
            string[] pengs = new string[2]{"agg", "sub"};
            Random numGen = new Random();
            int mepi = numGen.Next(1, 2);
            int mepi2 = numGen.Next(1, 2);
            string pemi = pengs[mepi];
            string pemi2 = pengs[mepi2];
            string whoMet = pemi + ", " + pemi2;
            return whoMet;
        }
        static int WutHap(int agg, int sub)
        {
            NumGen();
            switch (NumGen())
            {
                case ("agg, agg"):
                    --agg;
                    --agg;
                    break;
                case ("agg, sub"):
                    ++agg;
                    ++agg;
                    ++agg;
                    --sub;
                    break;
                case ("sub, agg"):
                    --sub;
                    ++agg;
                    ++agg;
                    ++agg;
                    break;
                case ("sub, sub"):
                    ++sub;
                    ++sub;
                    break;
            }
        }

    }

最佳答案

您可以使用 C# 7 语法从方法返回多个值:

static void Main(string[] args)
{
    var (a, b) = Foo();
}


private static (int, int) Foo()
{
    return (1, 2);
}

更新:

使用 Tuple<int, int> :

static void Main(string[] args)
{
    var (a, b) = GetMultipleValue();
    Tuple<int, int> tuple = GetMultipleValue();
}

public static Tuple<int, int> GetMultipleValue()
{
    return Tuple.Create(1, 2);
}

关于c# - 你如何在 C#/csharp 中返回 2 个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59356198/

相关文章:

c# - 如何创建一个所有数字组合的n维数组?

JavaScript 按年龄组对数组进行分组并查找最大日期

javascript - 为什么带有属性的数组会导致 JS 出现未定义错误

javascript - 使用javascript将文本文件读入变量

c# - 在此域数据建模场景中访问引用数据的正确方法是什么?

c# - Windows 窗体 : What's the right way to allow overlapping Controls?

c# - 在 Visual Studio 2010 中设计报表的教程?

Python:在循环中对变量执行用户定义的加法

PHP session 变量 : Error Undefined Variable

c# - 我应该如何对异常类的序列化进行单元测试?