原文: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. 原始聲明方式見上述Demo
2. 直接使用.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);
}
}
看這個代碼是不是和我們平時寫的"list.Where(p => p.Age > 18)"很像呢?沒錯Where等方法就是使用類似的方式來實現的。
好了,我總結完了,如有遺漏,還望補上,臣不盡感激。