2016-08-01 2 views
-1

Так что я пытаюсь сделать, это взять список пользовательских входов и поместить их непосредственно в массив. Я хотел бы сделать это, не назначая переменную для каждого входа, потому что может быть сотни.Возврат значения функции без назначения ее переменной

 static void writeAndWait(String statement, int millisecondsToWait) 
    { 
     Console.WriteLine(statement); 
     Thread.Sleep(millisecondsToWait); 
     return; 
    } 
    static void Main(string[] args) 
    { 
     //I am using ArrayLists because they will store as many values as needed wether it be 1 or 1,000,000 or more 
     ArrayList Name; //Declaring Name 
     ArrayList Time; //Declaring Time 
     ArrayList Path; //Declaring Path 
     Name = new ArrayList(); //Name will be used to store the names of the timers the user inputs 
     Time = new ArrayList(); //Time will be used to store the times of the timers the user inputs 
     Path = new ArrayList(); //Path will be used to store the path line of the timers the user inuts; 

     writeAndWait("Hello, if you want to add timers all you need to do is type a name and press enter, say how long you want the timer to run for in minutes, and then add a number 1-10 any timers with the same number at the end will run sycrnasly, and any timers with diferant nubers will run async", 2000); 
     Name.Add(Console.ReadKey().ToString()); 
     Console.WriteLine(Name[0]); 
    } 

Console.WriteLine просто возвращает «Console.ReadKey(). ToString())

Я хотел бы, чтобы вернуть ключ, который пользователь вводит. Или возвращаемое значение Console.ReadKey

+1

FYI, вы, вероятно, хотите использовать [Console.ReadLine] (https://msdn.microsoft.com/en-us/library/system.console.readline (V = vs.110) .aspx) вместо 'Console.ReadKey' –

+1

Почему бы не использовать' List 'вместо' ArrayList'? Также почему вы используете 'Console.ReadKey' вместо' Console.ReadLine', так как ваше сообщение говорит, чтобы ввести имя и нажать enter? – juharr

+0

Я просто использовал ReadKey в качестве теста. У меня возникли проблемы с чтением значений из списка, поэтому я переключился на ArrayLists. Если бы вы могли прокомментировать какой-то код, показывающий, как использовать Список , это было бы здорово. Но все еще возникает вопрос, как мне вернуть значение, а не команду acctuall? –

ответ

0

Не знаете, что именно вы здесь задаете, но использование структуры не позволит вам поддерживать отдельные массивы. Если у вас действительно есть динамическое количество аргументов, я могу изменить этот ответ для этого.

public struct TimerDescriptor 
{ 
    public string Name; 
    public string Time; 
    public string Path; 

    public static bool TryParse(string text, out TimerDescriptor value) 
    { 
     //check for empty text 
     if (string.IsNullOrWhiteSpace(text)) 
     { 
      value = default(TimerDescriptor); 
      return false; 
     } 

     //check for wrong number of arguments 
     var split = text.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries); 
     if (split.Length != 3) 
     { 
      value = default(TimerDescriptor); 
      return false; 
     } 

     value = new TimerDescriptor 
     { 
      Name = split[0], 
      Time = split[1], 
      Path = split[2] 
     }; 

     return true; 
    } 

    public override string ToString() 
    { 
     return Name + ' ' + Time + ' ' + Path; 
    } 
} 

static void writeAndWait(String statement, int millisecondsToWait) 
{ 
    Console.WriteLine(statement); 
    Thread.Sleep(millisecondsToWait); 
} 
static void Main(string[] args) 
{ 
    //I am using ArrayLists because they will store as many values as needed wether it be 1 or 1,000,000 or more 
    var timerDescriptors = new List<TimerDescriptor>(); 

    writeAndWait("Hello, if you want to add timers all you need to do is type a name and press enter, say how long you want the timer to run for in minutes, and then add a number 1-10 any timers with the same number at the end will run sycrnasly, and any timers with diferant nubers will run async", 2000); 

    var line = Console.ReadLine(); 
    TimerDescriptor descriptor; 
    if (TimerDescriptor.TryParse(line, out descriptor)) 
    { 
     timerDescriptors.Add(descriptor); 
     Console.WriteLine(descriptor); 
    } 
    else Console.WriteLine("Syntax error: wrong number of arguments. The syntax is: {Name} {Time} {Path} without the curly braces."); 
} 
Смежные вопросы