1、委托
委托是类(Class),因此在声明委托时,地位是与类平级,应该声明在namespace体下

2、代码
//使用Action调用不带返回值的方法
internal class Program { static void Main(string[] args) { ActionDemo actionDemo = new ActionDemo(); Action action = new Action(actionDemo.Report); action.Invoke(); //使用委托调用方法 action(); //使用委托调用方法的简化写法 actionDemo.Report(); //使用对象调用方法 } } class ActionDemo { public void Report() { Console.WriteLine("i hava 3 methods"); } public int Add(int a,int b) { return a + b; } public int Sub(int a,int b) { return a - b; } }
//使用Func<>委托调用带返回值的方法
internal class Program { static void Main(string[] args) { ActionDemo actionDemo = new ActionDemo(); Func<int, int, int> func1 = new Func<int, int, int>(actionDemo.Add); Func<int, int, int> func2 = new Func<int, int, int>(actionDemo.Sub); int result = 0; result = func1.Invoke(10, 20); Console.WriteLine(result); result = func2.Invoke(10, 20); Console.WriteLine(result); } } class ActionDemo { public void Report() { Console.WriteLine("i hava 3 methods"); } public int Add(int a,int b) { return a + b; } public int Sub(int a,int b) { return a - b; } }
3、

4、声明一个委托
public delegate int Calc(int x,int y); //声明一个返回值为int,参数列表为(int,int)的委托
5、委托的应用
internal class Program { static void Main(string[] args) { WrapFactory wrapFactory=new WrapFactory(); ProductFactory productFactory=new ProductFactory(); Box box = wrapFactory.WrapProduct(productFactory.MakePizza); Console.WriteLine(box.product.Name); } } class Product { public string Name { get; set; } } class Box { public Product product { get; set; } } class WrapFactory { public Box WrapProduct(Func<Product> getProduct) { Product product = getProduct(); Box box=new Box(); box.product= product; return box; } } class ProductFactory { public Product MakePizza() { Product product=new Product(); product.Name = "Pizza"; return product; } public Product MakeToyCar() { Product product=new Product(); product.Name = "Toy Car"; return product; } }
6、多播委托

泛型委托
internal class Program { static void Main(string[] args) { Mydel<string> mydel1 = new Mydel<string>(CalcString); Mydel<int> mydel = new Mydel<int>(Calc); } static int Calc(int a, int b) { return a+ b; } static String CalcString(string a, string b) { return (a + b); } } public delegate T Mydel<T>(T a, T b); //声明泛型委托,三个“T”的类型是一致的,通常用自带的Action()和Func()即可
浙公网安备 33010602011771号