所以我正在尝试编写一个程序来输入用户的字符串值。我正在尝试使用开关来确定“a”和“b”之间的按键。我不断收到以下错误:参数1:无法从'方法组'转换为'布尔'。
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
const string a = " You pressed a";
const string b = " You pressed b";
string input = Console.ReadLine();
switch(input)
{
case a:
ShowData(a);
break;
case b:
ShowData(b);
break;
default:
Console.WriteLine(" You did not type a or b");
Console.WriteLine();
Console.ReadLine();
break;
}
}
static void ShowData(string a)
{
Console.WriteLine(ShowData);
}
}
}
答案 0 :(得分:6)
尝试这些更正:
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
const string a = " You pressed a";
const string b = " You pressed b";
string input = Console.ReadLine();
switch (input)
{
case "a": // correction 1
ShowData(a);
break;
case "b": // correction 2
ShowData(b);
break;
default:
Console.WriteLine(" You did not type a or b");
Console.WriteLine();
Console.ReadLine();
break;
}
}
static void ShowData(string a)
{
Console.WriteLine(a); // correction 3
}
}
}
答案 1 :(得分:2)
您遇到的错误似乎是因为您正在尝试编写ShowData方法,
static void ShowData(string a)
{
Console.WriteLine(ShowData);
}
应该是:
static void ShowData(string a)
{
Console.WriteLine(a);
}
我会说你根本不需要ShowData方法,因为你也可以直接在你的交换机上写一个,但这取决于你。
这将消除错误,但我仍然只得到结果"你没有输入a或b"。这是因为您的案例不正确。由于您正在寻找字符串a,您的情况应该是
case "a":
而不是
case a:
更改此项将提供所需的行为。这是我最终的最终代码:
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
const string a = " You pressed a";
const string b = " You pressed b";
string input = Console.ReadLine();
switch (input)
{
case "a": //Case changed to "a" instead of a
ShowData(a); //Here, we could use Console.writeLine(a) directly if we wanted.
Console.WriteLine();
Console.ReadLine();
break;
case "b": //Case changed to "b" instead of b
ShowData(b); //Here, we could use Console.writeLine(b) directly if we wanted.
Console.WriteLine();
Console.ReadLine();
break;
default:
Console.WriteLine(" You did not type a or b");
Console.WriteLine();
Console.ReadLine();
break;
}
}
static void ShowData(string a)
{
Console.WriteLine(a); //Changed from ShowData to a
}
}
}
答案 2 :(得分:1)
您正在将ShowData传递给控制台。我想你打算写Console.WriteLine(a);
而不是Console.WriteLine(ShowData);