委托demo

 1 delegate bool Filter(string s);
 2 class test
 3 {
 4 static void Main()
 5 {
 6 Filter f=new Filter(A);
 7 Display(new string[]{"ant","line","yok"},f);
 8 }
 9 static bool A(string s)
10 {
11 return "N".CompareTo(s)>0;
12 }
13 static void Display(string[] Names,Filter f)
14 {
15 int count=0;
16 foreach(string str in Names)
17 if(f(str))
18 console.writeline("Item {0} is {1}",count++,str);
19 }
20 }

2.组播委托

 1 delegate void methodinvoker();
 2 class test
 3 {
 4 static void Main()
 5 {
 6 new test();
 7 }
 8 test()
 9 {
10 methodinvoker m=null;
11 m+=new methodinvoker(Foo);
12 m+=new methodinvoker(Goo);
13 m();
14 }
15 void Foo()
16 {
17 console.writeline("Foo");
18 }
19 void Goo()
20 {
21 console.writeline("Goo");
22 }
23 }

委托能处理的事情接口也能同样处理

 1  interface IFilter
 2 {
 3 bool Filter(string s);
 4 }
 5  class test
 6 {
 7 class A:IFilter
 8 {
 9 public bool Filter(string s)
10 {
11 return "N".CompareTO(s)>0;
12 }
13 static void Main()
14 {
15 A a=new A();
16 Display(new string[]{"ant","lion","yok"},IFilter f);
17 }
18 static void Display(string[] Names,IFilter f)
19 {
20 int count=0;
21 foreach(string s in Names)
22 if(f(s))
23 console.writeline("Item {0} is {1}",count++,s);
24 }
25 }
26 }

注:委托处理虽然根漂亮,但委托最好用在事件上。

原文地址:https://www.cnblogs.com/drake/p/3210488.html