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?";