我有一个声明,然后用户必须输入一个键 如果他们进入一个他们做一件事,另一件事,另一件事。
从我的Readline我有问题
“错误CS0029:无法将类型'int'隐式转换为'string'”。
这有什么问题因为我认为我有:
choice = Convert.ToInt32(Console.ReadLine());
编辑
所以现在我使用了Steve的答案(下面)
这会抛出此错误消息:
CS0029:无法将类型'int'隐式转换为'bool'
对于这一行,我想:
case 1:
// action for choice == 1
if(choice = 1|2)
Console.WriteLine("Choice {0} Selected",choice);
break;
答案 0 :(得分:0)
看起来你有:
string choice;
choice = Convert.ToInt32(Console.ReadLine());
由于Convert.ToInt32
返回int
,您需要将声明的choice
类型更改为int
(或创建新变量)。
int choice;
choice = Convert.ToInt32(Console.ReadLine());
答案 1 :(得分:0)
错误显然是由错误的整数赋值给字符串变量引起的。这可以通过多种方式解决,但最大的问题是,您无法阻止用户键入任何内容(字母,标题,标签),并且盲目地将任何用户类型转换为整数,从一开始就注定要失败。 / p>
在这种情况下,您应始终采取防御性方案并使用适当的转换方法
int choice;
if(!Int32.TryParse(Console.ReadLine(), out choice))
Console.WriteLine("You should enter a integer number");
else
{
switch(choice)
{
case 1:
// action for choice == 1
break;
case 2:
// action for choice == 2
break;
default:
// action for any other integer number
break;
}
}
Int32.TryParse将尝试将输入转换为整数。如果输入无法转换,则返回false,否则为true。
修改强>
按照您的编辑后,此行不会按照您的想法进行操作
if(choice = 1|2)
该行在值1和值2之间进行按位OR,得到值3,然后将值3赋值给变量 choice 。 if(3)
不是if语句所需的布尔表达式。
顺便说一句,您不需要此代码,因为在案例1 的开关内,您已经知道此时的选择值,您可以直接编写
Console.WriteLine("Choice {0} Selected",choice);
或者当你选择== 1
时你想做什么