如何根据用户响应进行计数?

问题描述 投票:0回答:2

我正在尝试创建一个将根据用户的响应增加的计数器。这是到目前为止我得到的代码:

        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 z递增。 Console.WriteLine(z)将返回我0,而不是我正在等待的2(当用户有2个正确答案时)。

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

如何获得这些结果?

c# counter pass-by-reference
2个回答
0
投票

参数z通过值传递,因为它不是引用类型(请考虑类的实例)。更新参数值的方式,需要通过引用传递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中了解有关通过引用传递值的更多信息


0
投票

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

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)

© www.soinside.com 2019 - 2024. All rights reserved.