定義:一段函數或表達式,直接嵌套在程序里面,沒有名稱;和c#中的委托有密切的聯系;
委托:相當于把函數傳遞到程序里;匿名:把沒有名稱的函數傳遞到程序里
1.三種寫法的區分:普通函數delegate獲取 | 匿名函數delegate獲取 | Lambda表達式函數delegate獲取
using System;
using System.Collections.Generic;
using System.Text;
namespace Anonymous
{
class Program
{
delegate void TestDelegate(string s);
static void MethodTest(string s)
{
Console.WriteLine(s);
}
static void Main(string[] args)
{
TestDelegate tdA = new TestDelegate(MethodTest);
//c# 2.0 匿名方法
TestDelegate tdB = delegate (string s) { Console.WriteLine(s); };
//c# 3.0 Lambda寫法
TestDelegate tdC = (x) => { Console.WriteLine(x); };
}
}
}
2.泛型代理的應用
現在知道了可以這么用,但是還不知道什么時候這么用。待日后再說。
目前還是覺得直接調用一個方法比較方便。我干嘛要獲得這個函數引用(delegate),然后通過這種方式調用函數?可能這種lambda和匿名函數中用到代理的地方比較多。看上去寫起來較為方便簡潔?
add:
看了Enumerable.Where 方法,就是跟這玩意一樣一樣的。
delegate 返回值泛型 方法名<定義用到的泛型1,定義用到的泛型2 .... >(傳入參數泛型)
using System;
using System.Collections.Generic;
using System.Text;
namespace Anonymous
{
delegate int del(int i);
delegate TResult Func<TArg0, TResult>(TArg0 arg0);
class Program
{
static void Main(string[] args)
{
Lambda();
Console.ReadLine();
}
private static void StartThread()
{
System.Threading.Thread t1 = new System.Threading.Thread
(delegate ()
{
Console.WriteLine("Hi! ");
Console.WriteLine("Here comes Wenxuejia!");
});
t1.Start();
}
private static void Lambda()
{
del myDelegate = (x) => { return x * x; };
Console.WriteLine(myDelegate(5));
Func<int, bool> myFunc = x => x == 5;
Console.WriteLine(myFunc(4));
Console.WriteLine(myFunc(5));
}
}
}