【问题标题】:How to make a counter based on user response?如何根据用户反应进行计数器?
【发布时间】:2020-05-05 05:37:01
【问题描述】:

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

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

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

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

【问题讨论】:

  • C# 方法参数默认具有值语义。您在方法中所做的更改不适用于您从 Main() 传递的对象。这里更好的方法是从方法中返回值 z。

标签: c# counter pass-by-reference


【解决方案1】:

int 和其他原始类型默认通过值传递,而引用类型(考虑类的实例)通过引用传递;这就是允许在方法返回后对参数的更改保持不变的原因。您更新参数值的方式,您需要通过引用传递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 了解有关传递值​​的更多信息

【讨论】:

    【解决方案2】:

    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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 2020-09-20
      • 1970-01-01
      • 2017-04-06
      • 1970-01-01
      • 2017-11-22
      相关资源
      最近更新 更多