Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 没有ifs的随机值?_C#_If Statement_Random - Fatal编程技术网

C# 没有ifs的随机值?

C# 没有ifs的随机值?,c#,if-statement,random,C#,If Statement,Random,有没有办法把它缩短? 我需要这样做,但要找到较短的选项,最好不要使用ifs。您可以将字符串移动到数组中,并按生成的数字对其进行索引: Random rd = new Random(); int question; question = rd.Next(1,2); if(question ==1) { label1.Text = "What is your name?"; } if(question ==2) { label1.Text = "How old are you?";

有没有办法把它缩短?
我需要这样做,但要找到较短的选项,最好不要使用ifs。

您可以将字符串移动到数组中,并按生成的数字对其进行索引:

Random rd = new Random();
int question;
question = rd.Next(1,2);
if(question ==1)
{
    label1.Text = "What is your name?";
}
if(question ==2)
{
    label1.Text = "How old are you?";
}

{完全讽刺的回答}

你想要短一点吗?怎么样

string[] texts = 
{
    "What is your name?", 
    "How old are you?"
};

int index = rd.Next(0, texts.Length);            
label1.Text = texts[index];

我用这个来说明,越短越好。您的代码经过编译,易于理解,并生成正确的结果(将在紧循环中多次调用
new Random()
的可能性进行模化)。

看起来是使用条件运算符的好地方。您可能还想阅读以下内容:
label1.Text = new Random().Next(1,2) == 1 ? "What is your name?" : "How old are you?";