初学C#语法,使用书上的例子模拟练习,编译的时候提示了一个错误,没想明白,请教各位错在哪里?using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace test
{
    class Calcdata
    {
        public delegate int delcalcdata(int x,int y);
        public int Add(int x, int y)
        {
            return x + y;
        }
        public int Sub(int x, int y)
        {
            return x - y;
        }
        public int Mul(int x, int y)
        {
            return x * y;
        }
        public int Div(int x, int y)
        {
            return x / y;
        }
        public int ComputerData(string flag, int x, int y)
        {
            int result; //计算结果
            flag = flag.ToLower();
            delcalcdata obj;
            switch (flag)
            {
                case "a":
                    obj = new delcalcdata(Add);
                    break;
                case "b":
                    obj = new delcalcdata(Sub);
                    break;
                case "c":
                    obj = new delcalcdata(Mul);
                    break;
                case "d":
                    obj = new delcalcdata(Div);
                    break;
            }
            result = obj(x, y);
            return result;
        }
    }
}

解决方案 »

  1.   

    switch 里加个 default: switch (flag)
    {
    ...
    default:
      obj = new delcalcdata(Add);
      break;
    }
      

  2.   

    或者初始化obj时给其赋空。
                int result; //计算结果
                flag = flag.ToLower();
                delcalcdata obj = null;
                switch (flag)
                {..            }