如何根据用户响应制作计数器?

How to make a counter based on user response?

我正在尝试制作一个计数器,它会根据用户的响应递增。这是我到目前为止得到的代码:

        string ok = "";
        int z = 0;
        test(ok, z);
        test1(ok, z);
        Console.WriteLine(z);
    }

        static void test(string ok, int z)
        {

            bool estok = false;
            while (!estok)
            {
                ConsoleKeyInfo saisie = Console.ReadKey(true);
                if (saisie.Key == ConsoleKey.A || saisie.Key == ConsoleKey.B)
                {
                    estok = true;
                    if (saisie.Key == ConsoleKey.A)
                    {

                        z++;
                    }

                    if (saisie.Key == ConsoleKey.B)
                    {
                        z--;
                    }
                }
                else
                {
                    estok = false;
                    Console.WriteLine("Error");
                }
            }


        }
            static void test1(string ok, int z)
            {
                bool estok = false;
                while (!estok)
                {
                    ConsoleKeyInfo saisie = Console.ReadKey(true);
                    if (saisie.Key == ConsoleKey.A || saisie.Key == ConsoleKey.B)
                    {
                        estok = true;
                        if (saisie.Key == ConsoleKey.A)
                        {
                            z++;
                        }

                        if (saisie.Key == ConsoleKey.B)
                        {
                            z--;
                        }
                    }
                    else
                    {
                        estok = false;
                        Console.WriteLine("Error");
                    }
                }
            }

我得到了 2 个函数(testtest1),它们都增加了 int zConsole.WriteLine(z) 将 return 我 0,代替我正在等待的 2(当用户有 2 个正确答案时)。

我认为增量不会发生,因为它在函数中并且 Console.WriteLine(z) 无法达到 z++。我怎样才能改变它?

我怎样才能得到这些结果?

int 和其他基本类型默认按值传递,而引用类型(想想 class 的实例)按引用传递;这就是允许在方法 returns 之后保留对参数的更改。您更新参数值的方式需要通过引用传递 z

static void test(string ok, int z) 成为 static void test(string ok, ref int z)

调用 test(ok, z); 变为 test(ok, ref z);

您可以从 C# Language Reference

中了解有关通过引用传递值的更多信息

int 的方法参数是值类型而不是引用类型,据我从您的问题中了解到,您可能需要在方法调用中使用 out 关键字或从您拥有的方法中使用 return。

int z1= z;
test(ok, out z1);
int z2=z;
test1(ok, out z2);

并且方法声明也必须更改为

static void test(string ok, out int z)


static void test1(string ok, out int z)

或者您可以直接在方法 test 和 test1 中简单地放置一个 Console.WriteLine(z)