委托和其委托的方法必須具有相同的簽名。簽名相同:1.參數類型相同 2.參數數量相同 3.返回值一致
例一
- class Program
- {
- public delegate int MathMethod(int x, int y);
- public int Add(int a, int b)
- {
- return a + b;
- }
- static void Main(string[] args)
- {
- MathMethod mm;
- Program p = new Program();
- mm = p.Add;// 相當于一個方法的容器
- Console.WriteLine("計算結果為{0}",mm(7,6));
- Console.ReadLine();
- }
- }
例二
- class Program
- {
- public delegate double MathMethod(double x, double y);
- double Add(double a, double b)
- {
- return a + b;
- }
- double Subtract(double a, double b)
- {
- return a + b;
- }
- double Multiply(double a, double b)
- {
- return a * b;
- }
- double Divide(double a, double b)
- {
- return a / b;
- }
- void DoCalculate(MathMethod mm)
- {
- Console.WriteLine("請輸入第一個數");
- double x = Convert.ToDouble(Console.ReadLine());
- Console.WriteLine("請輸入第二個數");
- double y = Convert.ToDouble(Console.ReadLine());
- Console.WriteLine("結果{0}",mm(x, y));
- Console.ReadLine();
- }
- static void Main(string[] args)
- {
- MathMethod mm;
- Program p = new Program();
- mm = p.Divide;
- p.DoCalculate(mm);
- }
- }
-----------------------------------------------------------
多路委托
- class Program
- {
- public delegate void SayThingToS(string s);
- void SayHello(string s)
- {
- Console.WriteLine("你好{0}", s);
- }
- void SayGoodBye(string s)
- {
- Console.WriteLine("再見{0}", s);
- }
- static void Main(string[] args)
- {
- // 方式一
- SayThingToS say1, say2, say3, say4;
- Program p = new Program();
- say1 = p.SayHello;
- say1("xy"); // 你好xy
- say2 = p.SayGoodBye;
- say2("xy"); // 再見xy
- say3 = say1 + say2;
- say3("xy"); // 你好xy,再見xy
- say4 = say3 - say1;
- say4("xy"); // 再見xy
- // 方式二
- SayThingToS s1 = new SayThingToS(p.SayHello);
- s1 += new SayThingToS(p.SayGoodBye);
- s1("xy"); // 你好xy,再見xy
- SayThingToS s2 = new SayThingToS(p.SayHello);
- s2 += new SayThingToS(p.SayGoodBye);
- s2 -= new SayThingToS(p.SayHello);
- s2("xy"); // 再見xy
- }
- }
-----------------------------------------------------------
泛型委托
- class Program
- {
- // 泛型委托,與普通委托類似,不同之處只在于使用泛型委托要指定泛型參數
- public delegate T MyGenericDelegate<T>(T obj1,T obj2);
- int AddInt(int x, int y)
- {
- return x + y;
- }
- string AddString(string s1, string s2)
- {
- return s1 + s2;
- }
- static void Main(string[] args)
- {
- Program p = new Program();
- MyGenericDelegate<int> intDel;
- intDel = p.AddInt;
- Console.WriteLine("int代理的值是{0}", intDel(100, 200));
- MyGenericDelegate<string> stringDel;
- stringDel = p.AddString;
- Console.WriteLine("string代理的值是{0}", stringDel("aaa", "bbb"));
- }
- }
為了方便開發,.NET基類庫針對在實際開發中最常用的情形提供了幾個預定義好的委托,這些預定義委托用得很廣,比如在編寫lambda表達式和開發并行計算程序時經常要用到他們。就是下面我的幾篇博客需要介紹的內容。
-----------------------------------------------------------
為了方便開發,.NET基類庫針對在實際開發中最常用的情形提供了幾個預定義好的委托,這些預定義委托用得很廣,比如在編寫lambda表達式和開發并行計算程序時經常要用到他們。
預定義泛型委托Func
- class Program
- {
- double AddInt(int x, int y)
- {
- return x + y;
- }
- string AddString(string s1, string s2)
- {
- return s1 + s2;
- }
- static void Main(string[] args)
- {
- Program p = new Program();
- // 以為前兩個參數為int,他們運行的結果為double,最后一個參數與AddInt返回值一致
- Func<int, int, double> funcInt = p.AddInt;
- Console.WriteLine("funcInt的值為{0}", funcInt(100, 300));
- Func<string, string, string> funcString = p.AddString;
- Console.WriteLine("funcString的值為{0}", funcString("aaa", "bbb"));
- }
- }
-----------------------------------------------------------
為了方便開發,.NET基類庫針對在實際開發中最常用的情形提供了幾個預定義好的委托,這些預定義委托用得很廣,比如在編寫lambda表達式和開發并行計算程序時經常要用到他們
對于函數返回值為空的情形,可以使用Action泛型委托
- class Program
- {
- // 對于函數返回值為空的情形,可以使用Action泛型委托
- void Showstring(string s)
- {
- Console.WriteLine("顯示的string值為{0}",s);
- }
- static void Main(string[] args)
- {
- Program p = new Program();
- Action<string> showstring = p.Showstring;
- showstring("xy");
- }
- }
-----------------------------------------------------------
此委托返回一個bool值,該委托通常引用一個"判斷條件函數"。
需要指出的是,判斷條件一般為“外部的硬性條件”,比如“大于50”,而不是由數據自身指定,不如“查找數組中最大的元素就不適合”。
例一
- class Program
- {
- bool IsGreaterThan50(int i)
- {
- if (i > 50)
- return true;
- else
- return false;
- }
- static void Main(string[] args)
- {
- Program p=new Program();
- List<int> lstInt = new List<int>();
- lstInt.Add(50);
- lstInt.Add(80);
- lstInt.Add(90);
- Predicate<int> pred = p.IsGreaterThan50;
- int i = lstInt.Find(pred); // 找到匹配的第一個元素,此處為80
- Console.WriteLine("大于50的第一個元素為{0}",i);
- List<int> all = lstInt.FindAll(pred);
- for (int j = 0; j < all.Count(); j++)
- {
- Console.WriteLine("大于50的數組中元素為{0}", all[j]); // 找出所有匹配條件的
- }
- Console.ReadLine();
- }
- }
例二
- class Staff
- {
- private double salary;
- public double Salary
- {
- get { return salary; }
- set { salary = value; }
- }
- private string num;
- public string Num
- {
- get { return num; }
- set { num = value; }
- }
- public override string ToString()
- {
- return "Num......" + num + "......" + "......" + "Salary......" + salary;
- }
- }
- class Program
- {
- bool IsSalaryGreaterThan5000(Staff s)
- {
- if (s.Salary > 5000)
- return true;
- else
- return false;
- }
- static void Main(string[] args)
- {
- Program p = new Program();
- List<Staff> allStaff = new List<Staff>
- {
- new Staff{Num="001",Salary=9999.9},
- new Staff{Num="002",Salary=8991},
- new Staff{Num="003",Salary=10000.8},
- new Staff{Num="004",Salary=4999.99}
- };
- Predicate<Staff> s = p.IsSalaryGreaterThan5000;
- Staff theFirstOne = allStaff.Find(s);
- Console.WriteLine(theFirstOne); // 找出第一個
- List<Staff> all = allStaff.FindAll(s);
- for (int i = 0; i < all.Count(); i++)
- {
- Console.WriteLine(all[i]); // 找出所有滿足條件的
- }
- Console.ReadLine();
- }
- }
-----------------------------------------------------------
- class Program
- {
- double AddInt(int x, int y)
- {
- return x + y;
- }
- string AddString(string s1, string s2)
- {
- return s1 + s2;
- }
- static void Main(string[] args)
- {
- Program p = new Program();、
- // 以為前兩個參數為int,他們運行的結果為double,最后一個參數與AddInt返回值一致
- Func<int, int, double> funcInt = p.AddInt;
- Console.WriteLine("funcInt的值為{0}", funcInt(100, 300));
- Func<string, string, string> funcString = p.AddString;
- Console.WriteLine("funcString的值為{0}", funcString("aaa", "bbb"));
- // 匿名方法
- Func<float, float, float> fucFloat = delegate(float x, float y)
- {
- return x + y;
- };
- Console.WriteLine("funcFloat的值為{0}", fucFloat(190.7F, 99999.9F));
- Console.ReadLine();
- }
- }
-----------------------------------------------------------
- class Program
- {
- double AddInt(int x, int y)
- {
- return x + y;
- }
- string AddString(string s1, string s2)
- {
- return s1 + s2;
- }
- static void Main(string[] args)
- {
- Program p = new Program();
- // 以為前兩個參數為int,他們運行的結果為double,最后一個參數與AddInt返回值一致
- Func<int, int, double> funcInt = p.AddInt;
- Console.WriteLine("funcInt的值為{0}", funcInt(100, 300));
- Func<string, string, string> funcString = p.AddString;
- Console.WriteLine("funcString的值為{0}", funcString("xy", "xy"));
- // 匿名方法
- Func<float, float, float> fucFloat = delegate(float x, float y)
- {
- return x + y;
- };
- Console.WriteLine("funcFloat的值為{0}", fucFloat(190.7F, 99999.9F));
- // Lambda表達式
- Func<string, string, string> funString2 = (x, y) => (x + y);
- Console.WriteLine("funString2的值為{0}", funString2("xy", "xy"));
- Console.ReadLine();
- }
- }
-----------------------------------------------------------
例一
- delegate void AppendStringCallback(string text);
- private void AppendString(string txt)
- {
- this.listView1.Items.Add(txt);
- }
- private void ReceiveDate()
- {
- AppendStringCallback appendStringCallback = new AppendStringCallback(AppendString);
- this.Invoke(appendStringCallback, new object[]
- { string.Format("{0},{1},{2}", str1, str2 + "號", iepAddress.ToString()) });
- }
例二
- namespace ThreadPoolDemo
- {
- public partial class ThreadForm : Form
- {
- // 定義delegate以便Invoke時使用
- private delegate void SetProgressBarValue(int value);
- // 跟SetProgressBarValue委托相匹配的方法
- private void SetProgressValue(int value)
- {
- progressBar.Value = value;
- }
- // 使用Invoke方法來設置進度條
- private void RunWithInvoke()
- {
- int value = progressBar.Value;
- while (value< progressBar.Maximum)
- {
- // 如果是跨線程調用
- if (InvokeRequired)
- {
- this.Invoke(new SetProgressBarValue(SetProgressValue), value++);
- }
- else
- {
- progressBar.Value = ++value;
- }
- }
- }
- public ThreadForm()
- {
- InitializeComponent();
- }
- private void btnInvoke_Click(object sender, EventArgs e)
- {
- progressBar.Value = 0;
- Thread thread = new Thread(new ThreadStart(RunWithInvoke));
- thread.Start();
- }
- }
- }
-----------------------------------------------------------
C#委托基礎系列原于2011年2月份發表在我的新浪博客中,現在將其般至本博客。
本文出自 “IT徐胖子的專欄” 博客,請務必保留此出處http://woshixy.blog.51cto.com/5637578/1070976
浙公網安備 33010602011771號