C#我遇到的问题是变量没有像我预期的那样发挥作用

Bee*_*nes 4 c# string int visual-studio

我试图模仿一个骰子滚动,如果死亡落在一定数量上然后它做了一些事情,如果它落在另一个数字上它会做其他事情.但是,我遇到了麻烦.它说if (hitPoints = 1)我收到错误的地方:

无法将类型'int'隐式转换为'string'.

但你可以清楚地看到它确实是一个字符串.对此问题的任何帮助将非常感谢,提前谢谢你.

Random r = new Random();
    int hit = r.Next(1, 5);
    string hitPoints = hit.ToString();


    EmbedBuilder builder = new EmbedBuilder();



    if (hitPoints = 1)
    { 
        builder.WithTitle("");
    }
Run Code Online (Sandbox Code Playgroud)

cla*_*ect 7

欢迎堆栈溢出!

我看到你已声明并指定hitpoints为字符串:

string hitPoints = hit.ToString();
Run Code Online (Sandbox Code Playgroud)

但在下面,你将它(我希望)与一个数字进行比较:

if (hitPoints = 1)
Run Code Online (Sandbox Code Playgroud)

那里有两个问题.首先,那不是比较运算符.其次,文字1不是字符串.

如果你真的想hitPoints成为一个字符串,并且你想比较它,1那么试试这个:

if (hitPoints == "1")
Run Code Online (Sandbox Code Playgroud)

附注:请允许我建议您不要将其hitPoints作为字符串存储,只是将其作为一个输出.您始终可以调用.ToString()现有hit变量:

int hit = r.Next(1, 5);

if (hit == 1) {
    // do a thing
}

// using newer string interpolation, implicit hit.ToString()
Console.WriteLine($"Hit was {hit}");

// using old format, implicit hit.ToString()
Console.WriteLine("Hit was {0}", hit);

// using old format, explicit hit.ToString()
Console.WriteLine("Hit was {0}", hit.ToString());
Run Code Online (Sandbox Code Playgroud)