纸上得来终觉浅,绝知此事要躬行。

 

委托(练习)

1 using System;
2  using System.Collections.Generic;
3  using System.Linq;
4  using System.Text;
5
6 namespace 委托_1
7 {
8 delegate void Del(int i, double j);
9 class Program
10 {
11 static void Main(string[] args)
12 {
13 Program m = new Program();
14 Del d = m.MultiplyNumbers;
15 Console.WriteLine("________________________________________");
16 for (int i = 1; i <= 5; i++)
17 {
18 d(i, 2.0);
19 }
20 Console.ReadKey(true);
21 }
22 void MultiplyNumbers(int m, double n)
23 {
24 Console.Write(m * n + " ");
25 }
26
27 }
28 }
29

 

结果:2   4   6   8   10

把方法赋给委托时,除了委托的invoke方法,其他赋值都不用带参数,用的时候再传参数。

例如上面的:Del d = m.MultiplyNumbers;      MultiplyNumber方法其实要有两个参数,因为只是给委托赋值。语法是这样的。。。所以用的时候再为MultiplyNumber带上参数。

下面这个例子是一样的,只是没有带参数调用了:

1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace 委托_2
7 {
8 delegate void Del();
9 public class SampleClass
10 {
11 public void InstanceMethod()
12 {
13 Console.WriteLine("_____________________________________");
14 }
15 static public void StaticMethod()
16 {
17 Console.WriteLine("++++++++++++++++++++++++");
18 }
19 }
20 class Program
21 {
22 static void Main(string[] args)
23 {
24 SampleClass sc=new SampleClass();
25 Del d = sc.InstanceMethod;
26 d();
27
28 d = SampleClass.StaticMethod;
29 d();
30 }
31 }
32 }
33

 

结果是:________________________________

           +++++++++++++++++++++++++++

posted on 2010-07-16 14:27  JRoger  阅读(288)  评论(0编辑  收藏  举报

导航