没有ifs的随机值?

时间:2016-03-30 17:46:42

标签: c# if-statement random

set -e

DIR=$PWD

for dir in ./projects/**/
do
    echo -e "\033[4;32mInstalling $dir\033[0m"
    cd $dir
    npm install & # takes a while, so do this in parallel
    cd $DIR
done

wait # continue once the background jobs are completed

for dir in ./projects/**/
do
    cd $dir
    echo -e "\033[4;32mBuilding $dir\033[0m"
    npm run build # Some projects use other projects, so build them in series
    cd $DIR
    echo -e "\n"
done

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

2 个答案:

答案 0 :(得分:8)

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

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

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

答案 1 :(得分:0)

{完全讽刺的回答}

你想要更短? <怎么样

label1.Text = new Random().Next(1,2) == 1 ? "What is your name?" : "How old are you?";

我用它来说明更短并不总是更好。您的代码编译,易于理解,并生成正确的结果(模块化在紧密循环中多次调用new Random()的可能性。)