如果变量= this,则执行此操作

时间:2017-11-05 05:17:49

标签: c# variables random numbers

我刚接触C#进行编码,我已经四处寻找答案,但没有一个对我有意义,我试图将变量设置为随机数,如果是等于1,执行此操作,如果等于2,请执行此操作。谢谢

代码:

if (goright == true)
            {
                Random rand = new Random();
                var x = rand.Next(1, 8);

                     if x = 1 ;
                    {
                        makeBullet2();
                        makeBullet3();
                        makeBullet4();
                    }

3 个答案:

答案 0 :(得分:0)

你想要if / else if:

if (x == 1)
{
    makeBullet1();
}
else if (x == 2)
{
    makeBullet2();
}
else
{
    // you can also include "else" without an "if" statement if you want a generic action to happen if none of the other cases are matched
}

或者您可以使用switch

switch (x)
{
    case 1:
        makeBullet1();
        break;
    case 2:
        makeBullet2();
        break;
    default:
        // similar to else
        break;
}

如果你发现自己必须检查很多单个值(例如x == 1,x == ...,x == n),那么switch语句可能会更好。如果你有复杂的逻辑(x> 1&& x< 5& y = 42&&!sunday),那么if语句会更好。

答案 1 :(得分:0)

在这种情况下,您可以使用如下所示的Switch语句:

Random rand = new Random();
var x = rand.Next(1, 8);

switch (x)
{
    case 1:
        makeBullet1();
        break;
    case 2:
        makeBullet2();
        break;
    case 3:
        makeBullet3();
        break;
    case 4:
        makeBullet4();
        break;
    default:
        // your code if no case was true
        break;          
}

答案 2 :(得分:0)

// Try this...
if (goright == true)
            {
                Random rand = new Random();
                var x = rand.Next(1, 3);

                     if(x == 1 )
                    {
                      /* What ever you want to do*/
                    }
                    else
                    {
                    /*if x==2 What ever you want to do*/
                    }
             }