C#“委托”学习笔记
2012-12-25 19:30
295 查看
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DelegateTest { public class test { static void Main(string[] args) { Class1 c = new Class1(); //用new操作把委托与一个方法关联 SayHello sh = new SayHello(c.SayHelloMethod); Console.WriteLine(sh("Wang")); //用等号把委托与一个方法关联 SayHello sh2 = c.SayHelloMethod; Console.WriteLine(sh2("Liu")); //委托与一个匿名方法关联 SayHello sh3 = delegate(string var) { Console.WriteLine("sh3!"); return var + ",how are you?"; }; Console.WriteLine(sh3("Jiang")); //组合委托,此时委托就能够依次执行多个方法 NumberHandle nh = new NumberHandle(c.DoubleNumber); NumberHandle nh2 = c.TrebleNumber; NumberHandle nh3 = nh + nh2; int num = 2; nh3(ref num); Console.WriteLine(""+num); //组合委托,若委托的方法有返回值,则返回值为最后一个被执行方法的返回值 SayHello sh4 = sh + sh3; Console.WriteLine(sh4("Zheng")); //lambda表达式:另一种把委托与匿名方法关联起来的方法 SayHello sh5 = var => var + ",Hello lambda"; Console.WriteLine(sh5("Guo")); Console.ReadLine(); } } delegate string SayHello(string val); delegate void NumberHandle(ref int num); class Class1 { public string SayHelloMethod(string name) { Console.WriteLine("SayHello Method!"); return name + ",Hello!"; } public void DoubleNumber(ref int num) { Console.WriteLine("Double it!"); num *= 2; } public void TrebleNumber(ref int num) { Console.WriteLine("Treble it!"); num *= 3; } } }
相关文章推荐
- [C#学习笔记之多线程1]使用ParameterizedThreadStart委托向线程函数传送参数
- 《C#高级编程》学习笔记------C#中的委托和事件(续)
- C#学习笔记--详解委托,事件与回调函数
- C#学习笔记(10)——再谈委托,不同国家问候的例子
- C#学习笔记五---委托
- C#学习笔记之泛型委托
- C#学习笔记8——C# 中的委托和事件
- C#学习笔记之一:委托
- C# 学习笔记_委托(二)Action与Func
- C#学习笔记19-委托和事件
- C#学习笔记-委托,event
- 《C#高级编程》学习笔记------C#中的事件和委托
- C#委托,事件最初浅的和最易看懂的学习笔记
- C# 学习笔记_委托(三)基于冒泡排序的拓展
- C#学习笔记17-Action委托和Func委托
- C#之委托概念认识学习笔记
- C#学习笔记-委托
- C#学习笔记:泛型委托Action<T>和Fun<TResult>
- C#教程第7讲委托1(学习笔记)
- C#学习笔记 委托和事件