繁体   English   中英

如何在文本框中显示 2 个值?

[英]How to display 2 values in a textbox?

我正在尝试使用 Visual Studio 在文本框中显示两个随机生成的数字。

这是我目前所拥有的......

int RandomNumber(int min = 0, int max = 100)
            {
                Random random = new Random();
                return random.Next(min, max);
            }
            int RandomNumber2(int min = 0, int max = 100)
            {
                Random random = new Random();
                return random.Next(min, max);
            }
            txtQuestion.Enabled = true;

        string num1 = Convert.ToString(RandomNumber());
        string num2 = Convert.ToString(RandomNumber2());

        txtQuestion.Text = ("{0} + {1} = ?", num1, num2);

但是,最后一行出现错误“无法将类型'(string, string num1, string num2)'隐式转换为'string'”

我应该如何在文本框中 output 这些随机生成的数字?

嗨,下面是编辑后的代码,可以满足我的需要。 感谢所有帮助:)

Random random1 = new Random();

我在全局范围内调用了上面的 function,这样我每次需要新的随机数时都可以参考它。 下面是我在 function 中使用它来调用两个不同的随机数并将它们显示在文本框中的方法。

            int randomNumber1 = random1.Next(0, 10);
        int randomNumber2 = random1.Next(0, 10);

        string num1 = Convert.ToString(randomNumber1);
        string num2 = Convert.ToString(randomNumber2);

        txtQuestion.Text = string.Format ("{0} + {1} = ?", num1, num2);

正如@John 所说,您正在使用 ValueTuple。 您可以在此处或在 msdn 上了解有关 ValueTuple 的更多信息。 但是我提供的链接显示的代码与您编写的代码几乎相同。

您想要做的是使用 string.Format:

txtQuestion.Text = string.Format("{0} + {1} = ?", num1, num2);

或更简洁的字符串插值:

txtQuestion.Text = $"{num1} + {num2} = ?";

并显示这样的答案:

Random random = new Random();
int nextRandom() => random.Next(0, 100);
int num1 = nextRandom();
int num2 = nextRandom();
txtQuestion.Text = $"{num1} + {num2} = {num1 + num2}";
// If you have a method that computes the result you can also call it inside
txtQuestion.Text = $"{num1} + {num2} = {SomeFunction(num1, num2)}";

要解决您的随机问题,您必须只创建一次随机实例。

class MyClass
{
    // Use the same instance of Random.
    private Random _random = new Random();

    public int RandomNumber()
    {
        return _random.Next(0, 100);
    }

    public void DisplayText()
    {
        int num1 = RandomNumber();
        int num2 = RandomNumber();
        txtQuestion.Text = $"{num1} + {num2} = {num1 + num2}";
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM