Дополнительные параметры с пользовательским вводом с помощью C#

#visual-studio #c#-4.0 #optional-parameters

Вопрос:

Поэтому я пытаюсь заставить свое консольное приложение в Visual Studio принять пустой ответ от пользователя, однако после двух пустых ответов я получаю сообщение об ошибке. Я использую try/catch вместо if/else, и кажется, что мой необязательный параметр просто работает не так, как я считаю нужным. Любая помощь будет очень признательна!

Мой программный код.cs:

 static void Main(string[] args)
    {
        try
        {
            Operator operatorObject = new Operator();
            Console.WriteLine("Pick a number:");
            int data = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Pick another number--optional");
            int input = Convert.ToInt32(Console.ReadLine());

            int result = operatorObject.operate(data, input);


            Console.WriteLine(result);
            Console.ReadLine();
        }
        catch
        {
            Operator operatorObject = new Operator();
            int data = Convert.ToInt32(Console.ReadLine());
            
            int result = operatorObject.operate(data);
            Console.WriteLine(result);


            Console.ReadLine();
        }
    }
}
 

мой код класса:

 public class Operator
{
    public int operate(int data, int input = 0)
    {
        return data   input;
    }
}
 

Ответ №1:

Вы можете использовать пробный анализ, подобный этому:

 static void Main(string[] args)
{
  try
  {
    Operator operatorObject = new Operator();
    Console.WriteLine("Pick a number:");
    int data = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("Pick another number--optional");
    int input;
    bool inputResult = Int32.TryParse(Console.ReadLine(), out input);

    int result = operatorObject.operate(data, input);

    Console.WriteLine(result);
    Console.ReadLine();
  }
  catch
  {
    Operator operatorObject = new Operator();
    int data;
    bool dataResult = Int32.TryParse(Console.ReadLine(), out data);
    int result = operatorObject.operate(data);
    Console.WriteLine(result);

    Console.ReadLine();
  }
}