我有这个解决方案,我正在努力,并尝试返回3个不同的userInput 对Main的问题。这就是我目前所拥有的。
public static string GetInput()
{
//declared variables
string userInput;
string outputTitle;
Console.Write("Enter your name: ");
userInput= Console.ReadLine();
Console.Write("Enter your age: ");
userInput = Console.ReadLine();
Console.Write("Enter the Gas Mileage: ");
userInput = Console.ReadLine();
return userInput;
}
我设置它的方式我永远不会通过("输入你的名字");题。有什么更好的方法来解决这个问题?
userName = InputUtilities.GetInput(userName); //错误2方法' GetInput'没有重载需要1个参数
Console.Write("您的姓名是:{0}",userName);
答案 0 :(得分:9)
使用类来定义要捕获的输入,并返回该输入。
public class UserDetails
{
public string Name {get;set;}
public string Age {get;set;}
public string Mileage {get;set;}
}
public static UserDetails GetInput()
{
//declared variables
//string userInput;
//string outputTitle;
var userD = new UserDetails();
Console.Write("Enter your name: ");
userD.Name = Console.ReadLine();
Console.Write("Enter your age: ");
userD.Age = Console.ReadLine();
Console.Write("Enter the Gas Mileage: ");
userD.Mileage = Console.ReadLine();
return userD;
}
编辑:使用输出参数的示例。
void Main()
{
string name, age, mileage;
GetInput(out name, out age, out mileage);
//use name, age and mileage here.
}
public static void GetInput(out string pName, out string pAge, out string pMileage)
{
Console.Write("Enter your name: ");
pName = Console.ReadLine();
Console.Write("Enter your age: ");
pAge = Console.ReadLine();
Console.Write("Enter the Gas Mileage: ");
pMileage = Console.ReadLine();
}
答案 1 :(得分:1)
如果要返回3个值,则必须有3个位置才能放置它们:
public static List<String> GetInput()
{
//declared variables
string userInput;
List<String> userInputs = new List<String>();
Console.Write("Enter your name: ");
userInput= Console.ReadLine();
userInputs.Add(userInput);
Console.Write("Enter your age: ");
userInput = Console.ReadLine();
userInputs.Add(userInput);
Console.Write("Enter the Gas Mileage: ");
userInput = Console.ReadLine();
userInputs.Add(userInput);
return userInput;
}
答案 2 :(得分:0)
您要将用户为每个问题输入的值分配给同一个变量。每次写入都会覆盖之前的值,这意味着您应该只得到最后一个问题的答案(&#34;输入Gas Mileage&#34;)。有几种方法可以解决这个问题:
1)将每个连续的答案附加到同一个字符串(不推荐)。
2)创建一些对象来存储所有答案(类或列表)。
3)使用参数。
由于已经解释了其他两个答案,因此输出了以下参数:
public static void GetInput(out string pName, out string pAge, out string pMileage)
{
// do stuff here ....
}
答案 3 :(得分:0)
或者
public static object GetInput()
{
Console.Write("Enter your name: ");
var _name = Console.ReadLine();
Console.Write("Enter your age: ");
var _age = Console.ReadLine();
Console.Write("Enter the Gas Mileage: ");
vae _mileage = Console.ReadLine();
return new { name = _name, age = _age, mileage = _mileage };
}
或者
public static dynamic GetInput()
{
//declared variables
dynamic userinputs;
Console.Write("Enter your name: ");
var _name = Console.ReadLine();
Console.Write("Enter your age: ");
var _age = Console.ReadLine();
Console.Write("Enter the Gas Mileage: ");
vae _mileage = Console.ReadLine();
userinputs.name = _name;
userinputs.age = _age;
userinputs.mileage = _mileage;
return userinputs;
}