1、委托的异步调用
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace _04_委托的异步调用 { delegate string DelTest(string name); public partial class Form1 : Form { public Form1() { InitializeComponent(); this.Text = ""; } DelTest del; private void button1_Click(object sender, EventArgs e) { del= Test; del += Test; //委托的异步调用 IAsyncResult ir = del.BeginInvoke("abc",Callback,null); //while (!ir.IsCompleted) //{ // this.Text += "*"; // System.Threading.Thread.Sleep(300); //} MessageBox.Show("Test"); } void Callback(IAsyncResult ir) { //接收BeginInvoke 传过来的最后一个参数 //ir.AsyncState string t = del.EndInvoke(ir); MessageBox.Show(t); MessageBox.Show("over"); } string Test(string name) { for (int i = 0; i < 10000; i++) { Console.WriteLine(i); } return name; } } }
2、委托
public delegate int DelCompare(object o1,object o2); public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { object[] array = {"abc","ab","aaaaaaaa","abcde","a" }; object o = GetMax(array, CompareString); MessageBox.Show(o.ToString()); } private int CompareString(object o1, object o2) { string s1 = o1.ToString(); string s2 = o2.ToString(); return s1.Length - s2.Length; } public object GetMax(object[] array,DelCompare del) { object max = array[0]; for (int i = 1; i < array.Length; i++) { if (del(max,array[i]) < 0) { max = array[i]; } } return max; }
3、委托详解
public class BubbleSort { public delegate int MyDelegate(int a); //声明一个返回int 类型的传入参数为int的委托函数 static void Main(string[] arg) { MyDelegate dele1, dele2; dele1 = new MyDelegate(JiSuan.getNum);//初始化委托 dele2 = new MyDelegate(JiSuan.getNum2); var m = dele1(1); var n = dele1(1) + dele2(1); } } public class JiSuan { public static int getNum(int a) { return 3; } public static int getNum2(int a) { return 6; } }
委托的加减乘除运算
http://www.bubuko.com/infodetail-1450934.html
public class BubbleSort { public delegate int MyDelegate(int a,int b); static void Main(string[] arg) { var m=GetCaozuo()(9,3); } private static MyDelegate GetCaozuo() { return JiSuan.jia; } } public class JiSuan { public static int jia(int a, int b) { return a + b; } public static int jian(int a, int b) { return a -b; } public static int cheng(int a, int b) { return a * b; } public static int chu(int a, int b) { return a / b; } }
委托方法的加减 用于顺序执行
dele = JiSuan.jia;
dele += JiSuan.jian;
dele += JiSuan.cheng;
dele += JiSuan.chu;