c# - 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("");
}
解决方案
欢迎来到堆栈溢出!
我看到您已声明并分配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());
推荐阅读
- lftp - 使用 LFTP 如果存在,我如何将特定文件发送到服务器覆盖?
- xamarin.android - 替换viewpager Mvvmcross中的片段
- c - 服务器没有收到来自客户端的信息?
- facebook - 以合法方式从 Facebook 提取公共数据
- javascript - Laravel Homestead 制作相同的本地(Windows)和服务器(Linux)
- batch-file - 用逗号分隔批处理中的标记,但字符串中有空格
- android-studio - Android Studio - 向主工具栏添加撤消和重做按钮 - 3.2.1 更新
- python - 使用python将数据附加到JSON文件
- sql - 使用可变参数构造 Web 服务的 URL
- android - 在“onActivityResult”收到的意图不包含我的额外内容