C# 委托
一、委托
1、Action
new Action(方法);
委派:无返回值
2、FunC
委派:有返回值
new Func<参数类型和返回值类型>(方法);
using Mysqlx.Notice; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ClassAndIn { internal class Program { static void Main(string[] args) { Calculation calculation = new Calculation(); // action 没有返回值 Action action = new Action(calculation.Print); action(); // 执行 // Func // <> 里面是参数类型和返回值类型 Func<int, int, int> func = new Func<int, int, int>(calculation.Add); // 使用 int a = 10; int b = 20; int c = 0; c = func(a, b); Console.WriteLine("{0}+{1}={2}", a, b, c); } } class Calculation { public void Print() { Console.WriteLine("Hello, World!"); } public int Add(int x, int y) { return x + y; } public int Sub(int x, int y) { return x- y; } } }
二、自定义委托
1、语法
a、定义
pulic delegate 返回值类型 委托名(参数类型);
b、执行
委托名 变量名 = new 委托名()
2、案例
using Mysqlx.Notice; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ClassAndIn { // 声明委托 public delegate double Cal(double a, double b); internal class Program { static void Main(string[] args) { Calculator calculator = new Calculator(); // 调用委托 Cal cal1 = new Cal(calculator.Add); double x = 20; double y = 40; double z = 0; z = cal1(x, y); Console.WriteLine(z); } } class Calculator { public double Add(double x, double y) { return x + y; } public double Sub(double x, double y) { return x - y; } public double Mul(double x, double y) { return x * y; } public double Div(double x, double y) { return x / y; } } }