Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.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#我遇到了变量不按我预期的那样运行的问题_C#_String_Visual Studio_Int - Fatal编程技术网

C#我遇到了变量不按我预期的那样运行的问题

C#我遇到了变量不按我预期的那样运行的问题,c#,string,visual-studio,int,C#,String,Visual Studio,Int,我试图模拟骰子滚动,如果骰子落在某个数字上,那么它会做一些事情,如果它落在另一个数字上,那么它会做其他事情。然而,我在这方面遇到了麻烦。其中显示if(hitPoints=1)我得到了错误: 无法将类型“int”隐式转换为“string” 但你可以清楚地看到,它确实是一根弦。在此问题上的任何帮助都将不胜感激,提前谢谢 Random r = new Random(); int hit = r.Next(1, 5); string hitPoints = hit.ToString();

我试图模拟骰子滚动,如果骰子落在某个数字上,那么它会做一些事情,如果它落在另一个数字上,那么它会做其他事情。然而,我在这方面遇到了麻烦。其中显示
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("");
    }

欢迎来到堆栈溢出

我看到您已将
生命点
声明并分配为字符串:

string hitPoints = hit.ToString();
但在下面,您将(我希望)与一个数字进行比较:

if (hitPoints = 1)
这里有两个问题。首先,这不是比较运算符。其次,文本
1
不是字符串

如果您确实希望
命中点
成为字符串,并且希望将其与
1
进行比较,请尝试以下操作:

if (hitPoints == "1")
旁注:请允许我建议您不要将命中点存储为字符串,而只是将其作为一个字符串输出。您始终可以对现有的
hit
变量调用
.ToString()

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());
if(hit==1)