C#错误:必须在控制离开当前方法之前分配out参数

时间:2015-09-17 15:36:09

标签: c#

错误所指的变量是aNumber on line(32,17),我该如何解决?

using System;
class Calculation
{
    public static void Main(string[] data)
    {
        double result = Convert.ToDouble( data[0]);
        char op;
        double number;
        GetData(out op, out number);
        while (op != 'q' && op != 'Q')
        {
            switch (op)
            {
                case '+':
                    result += number;
                    break;
                case '-':
                    result -= number;
                    break;
                case '*':
                    result *= number;
                    break;
                case '/':
                    result /= number;
                    break;
            }
            Console.WriteLine("Result = " + result.ToString());
            GetData(out op, out number);
        }       
    }

    static void GetData(out char anOperator, out double aNumber)
    {
        string line;
        Console.Write("Enter an opertor and a number or 'q' to quit: ");
        line = Console.ReadLine();
        anOperator = Convert.ToChar(line.Substring(0, 1));
        if (anOperator != 'q' && anOperator != 'Q')
            aNumber = Convert.ToDouble(line.Substring(2));
    }
}

1 个答案:

答案 0 :(得分:1)

将此添加到GetData方法:

aNumber = 0;

像这样:

static void GetData(out char anOperator, out double aNumber)
{
      string line;
      Console.Write("Enter an opertor and a number or 'q' to quit: ");
      line = Console.ReadLine();
      anOperator = Convert.ToChar(line.Substring(0, 1));
      if (anOperator != 'q' && anOperator != 'Q')
           aNumber =  Convert.ToDouble(line.Substring(2));
      else
           aNumber = 0;
}