首页 > 解决方案 > C# I am having trouble with variables not acting as I would expect

问题描述

I am trying to emulate a dice rolling and if the die lands on a certain number then it does something, and if it lands on another number it does something else. However, I am having trouble with this. Where it says if (hitPoints = 1) I am getting the error:

Cannot implicitly convert type 'int' to 'string.'

But you can clearly see that it is indeed a string. Any help on this problem would be very much appreciated, thank you in advance.

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


    EmbedBuilder builder = new EmbedBuilder();



    if (hitPoints = 1)
    { 
        builder.WithTitle("");
    }

标签: c#stringvisual-studioint

解决方案


欢迎来到堆栈溢出!

我看到您已声明并分配hitpoints为字符串:

string hitPoints = hit.ToString();

但在此之下,您正在将其(我希望)与一个数字进行比较:

if (hitPoints = 1)

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

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

if (hitPoints == "1")

旁注:请允许我建议您不要将其存储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());

推荐阅读