(转)委托的N种写法,你喜欢哪种?

王朝学院·作者佚名  2016-05-16
窄屏简体版  字體: 小  |  中  |  大  |  超大  

(转)委托的N种写法,你喜欢哪种?原文:http://www.cnblogs.com/FreeDong/archive/2013/07/31/3227638.html

一、委托调用方式

1. 最原始版本: delegate string PlusStringHandle(string x, string y); class PRogram { static void Main(string[] args) { PlusStringHandle pHandle = new PlusStringHandle(plusString); Console.WriteLine(pHandle("abc", "edf")); Console.Read(); } static string plusString(string x, string y) { return x + y; } }

2. 原始匿名函数版:去掉“plusString”方法,改为 PlusStringHandle pHandle = new PlusStringHandle(delegate(string x, string y) { return x + y; }); Console.WriteLine(pHandle("abc", "edf"));

3. 使用Lambda(C#3.0+),继续去掉“plusString”方法(以下代码均不再需要该方法) PlusStringHandle pHandle = (string x, string y) => { return x + y; }; Console.WriteLine(pHandle("abc", "edf"));

还有更甚的写法(省去参数类型)

PlusStringHandle pHandle = (x, y) => { return x + y; }; Console.WriteLine(pHandle("abc", "edf"));

如果只有一个参数

delegate void WriteStringHandle(string str); static void Main(string[] args) { //如果只有一个参数 WriteStringHandle handle = p => Console.WriteLine(p); handle("lisi"); Console.Read(); }

二、委托声明方式

1. 原始声明方式见上述Demo2. 直接使用.NET Framework定义好的泛型委托 Func 与 Action ,从而省却每次都进行的委托声明。 static void Main(string[] args) { WritePrint<int>(p => Console.WriteLine("{0}是一个整数", p), 10); Console.Read(); } static void WritePrint<T>(Action<T> action, T t) { Console.WriteLine("类型为:{0},值为:{1}", t.GetType(), t); action(t); }

3. 再加上个扩展方法,就能搞成所谓的“链式编程”啦。 class Program { static void Main(string[] args) { string str = "所有童鞋:".plusString(p => p = p + " girl: lisi、lili\r\n").plusString(p => p + "boy: wangwu") ; Console.WriteLine(str); Console.Read(); } } static class Extentions { public static string plusString<TParam>(this TParam source, Func<TParam, string> func) { Console.WriteLine("字符串相加前原值为:{0}。。。。。。", source); return func(source); } }

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航