委托笔记
刚写了段程序,总算稍微理解了下委托,留下备忘。
定义:
1 public delegate string DelegateTest(string sss);
类中实例化委托:
1 public class TestClass
2 {
3 public event DelegateTest _delegateTest;
4
5 public string BeginDelegate()
6 {
7 if (_delegateTest != null)
8 return _delegateTest("ssssssss");
9 else
10 return "1331";
11 }
12 }
2 {
3 public event DelegateTest _delegateTest;
4
5 public string BeginDelegate()
6 {
7 if (_delegateTest != null)
8 return _delegateTest("ssssssss");
9 else
10 return "1331";
11 }
12 }
调用的时候,直接调用TestClass中的BeginDelegate方法,
为实例化的委托添加方法
1 public class ObjClass
2 {
3 public ObjClass(TestClass tc)
4 {
5 tc._delegateTest += new DelegateTest(typeBj);
6 }
7
8 public string typeBj(string sssss)
9 {
10 Console.WriteLine(sssss);
11
12 return sssss + "123132132";
13 }
14 }
15
16 public class ObjClass1
17 {
18 public ObjClass1(TestClass tc)
19 {
20 tc._delegateTest += new DelegateTest(typeJJ);
21 }
22
23 public string typeJJ(string sssssss)
24 {
25 Console.WriteLine(sssssss + "123123132");
26
27 return sssssss + "abcdefghijklmn";
28 }
29 }
2 {
3 public ObjClass(TestClass tc)
4 {
5 tc._delegateTest += new DelegateTest(typeBj);
6 }
7
8 public string typeBj(string sssss)
9 {
10 Console.WriteLine(sssss);
11
12 return sssss + "123132132";
13 }
14 }
15
16 public class ObjClass1
17 {
18 public ObjClass1(TestClass tc)
19 {
20 tc._delegateTest += new DelegateTest(typeJJ);
21 }
22
23 public string typeJJ(string sssssss)
24 {
25 Console.WriteLine(sssssss + "123123132");
26
27 return sssssss + "abcdefghijklmn";
28 }
29 }
主方法:
1 public class MainClass
2 {
3 public static void Main()
4 {
5 TestClass tc = new TestClass();
6
7 ObjClass oc = new ObjClass(tc);
8 ObjClass1 oc1 = new ObjClass1(tc);
9 string s = tc.BeginDelegate();
10
11 Console.ReadKey();
12 }
13 }
2 {
3 public static void Main()
4 {
5 TestClass tc = new TestClass();
6
7 ObjClass oc = new ObjClass(tc);
8 ObjClass1 oc1 = new ObjClass1(tc);
9 string s = tc.BeginDelegate();
10
11 Console.ReadKey();
12 }
13 }
主方法里调用tc.BeginDelegate();
清除委托中的方法
1 tc._delegateTest -= new DelegateTest(oc1.typeJJ);