C#委託Code

 class Program
    {
        delegate double ProcessDelegate(double param1, double param2);

        static double Multiply(double param1, double param2)
        {
            return param1 * param2;
        }

        static double Divide(double param1, double param2)
        {
            return param1 / param2;
        }

        static void Main(string[] args)
        {
            ProcessDelegate process;
            Console.WriteLine("輸入兩個數以逗號隔開:");
            string input = Console.ReadLine();
            int commaPos = input.IndexOf(',');

            double param1 = Convert.ToDouble(input.Substring(0, commaPos));
            double param2 = Convert.ToDouble(input.Substring(commaPos + 1,input.Length - commaPos - 1));

            Console.WriteLine("輸入 M 進行乘法 或者 D 進行除法:");
            input = Console.ReadLine();
            if (input == "M")
            //process = new ProcessDelegate(Multiply);
            {
                //委託的第一種寫法
                process = Multiply;
              //  process(param1, param2);
            }
            else
                //委託的第二種寫法
                process = new ProcessDelegate(Divide);
            Console.WriteLine("結果: {0}", process(param1, param2));
            Console.ReadKey();
        }
    }

此代碼爲《C#入門經典》源碼有進行學習後,發表到博客裏,爲提醒之後使用!ide

相關文章
相關標籤/搜索