委托和其委托的方法必须具有相同的签名。签名相同: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