委托(delegate)是一种存储函数引用的类型,听起来有点高深,但其机制非常简单
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { delegate int process(int a, int b); static int m(int a, int b) { return a + b; } static int d(int a,int b) { return a - b; } static void Main(string[] args) { process type; string input_val; int where_is_pos,num1,num2; int result = 0; Console.WriteLine("enter two numbers:"); input_val = Console.ReadLine(); where_is_pos = input_val.IndexOf(','); num1 = Convert.ToInt32(input_val.Substring(0, where_is_pos)); num2 = Convert.ToInt32(input_val.Substring(where_is_pos + 1, input_val.Length - where_is_pos - 1)); Console.WriteLine("enter m or d"); input_val = Console.ReadLine(); if (input_val == "m") { type = new process(m); result = type(num1, num2); } if (input_val == "d") { type = new process(d); result = type(num1, num2); } Console.WriteLine("result = {0}", result); } } }