class AddItemOption
{
//Fields that contain class data
string input = Console.ReadLine();
//Methods that define class functionality
public string myFunction(string Value)
{
switch (input)
{
case "Umbrella":
Console.WriteLine("Umbrella is selected");
break;
case "Rain Coat":
Console.WriteLine("Raincoat is selected");
break;
case "Boots":
Console.WriteLine("Boots is selected");
break;
case "Hood":
Console.WriteLine("Hood is selected");
break;
default:
Console.WriteLine("Input not reconized, please choose another item");
break;
}
}
我收到错误“并非所有代码路径都返回值”。它来自myFunction(字符串值)。我不知道如何返回这个,或者在参数中添加什么以使其工作。我也需要它下面的东西吗?我是新上课的。请告诉我,如果我这样做是错误的,或者这是switch语句应该去的地方!
public AddItemOption(string input)
{
}
来自Shyju我改为:
class AddItemOptionOne
{
//Fields that contain class data
string input = Console.ReadLine();
//Methods that define class functionality
public string myFunction(string Value)
{
switch (input)
{
case "Key Chain":
return "Key Chain is selected";
break;
case "Leather Armor":
return "Leather Armor is selected";
break;
case "Boots":
return "Boots is selected";
break;
case "Sword":
return "Sword is selected";
break;
default:
return "Input not reconized, please choose another item";
break;
}
}
然而,它不承认休息。 “检测到无法访问的代码”
答案 0 :(得分:5)
您的方法的返回类型为string
。这意味着您的方法应始终返回某些字符串。但是你没有返回一个字符串。而是使用WriteLine
方法将其写入控制台。
所以改变
Console.WriteLine("Umbrella is selected");
到
return "Umbrella is selected";
或强>
您可以将方法的返回类型更改为void
。
public void myFunction(string Value)
{
//your current fancy stuff here
Console.WriteLine("My method dont have a return type");
}
编辑:根据问题编辑AS。
return
语句将从您的方法中取出控件。这意味着下一行(break
)将不会被执行。所以删除break语句。
case "Key Chain":
return "Key Chain is selected";
答案 1 :(得分:2)
嗯......你没有从你的函数返回任何东西,所以把它改成
public void myFunction(string Value)
答案 2 :(得分:2)
试试这个:
class AddItemOptionOne
{
//Methods that define class functionality
public string myFunction(string input)
{
string result = string.Empty;
switch (input)
{
case "Key Chain":
result = "Key Chain is selected";
break;
case "Leather Armor":
result = "Leather Armor is selected";
break;
case "Boots":
result = "Boots is selected";
break;
case "Sword":
result = "Sword is selected";
break;
default:
result = "Input not reconized, please choose another item";
break;
}
return result;
}
}