using System;
namespace 匿名函數
{
class Program
{
delegate void TestDelegate(string s);
static void M(string s)
{
Console.WriteLine("A參數為:{0}", s);
}
static void Main(string[] args)
{
//1. 委托的基本寫法,及調用
TestDelegate testDeleA = new TestDelegate(M);//通過委托的實例化將之與方法綁定
testDeleA("hahahah");
//2. 使用匿名表達式構造委托調用方法
//C#2.0 Anonymous Method,其結構為:delegate+(各個參數)+{函數體}
TestDelegate testDeleB = delegate (string s) { Console.WriteLine("B參數為:{0}", s); };//直接通過delegate聲明將之與函數體綁定
testDeleB("hehehehe");
//C#3.0, 引入lamda表達法,Lambda Expression
TestDelegate testDeleC = (x) => { Console.WriteLine("C參數為:{0}", x); };
testDeleC("hohoho");
Console.ReadKey();
}
}
}
using System;
namespace 匿名函數
{
class Program
{
static void Main(string[] args)
{
//調用線程
StartThread();
Console.ReadKey();
}
private static void StartThread()
{
//創建線程
System.Threading.Thread t1 = new System.Threading.Thread
(
delegate ()//參數不能使用ref、out這種關鍵字修飾,以及匿名方法不能放在is關鍵字左邊
{
//函數體中不能有unsafe code
Console.Write("Helo, ");
Console.WriteLine("World!");
}
);
//開啟線程
t1.Start();
}
}
}
using System;
namespace 匿名函數
{
class Program
{
delegate int del(int i);
delegate TResult Func<TArg, TResult>(TArg arg);
static void Main(string[] args)
{
Lambda();
Console.ReadKey();
}
private static void Lambda()
{
//() => {}
del myDelegate = x => x * x;//當參數只有一個時可以不帶括號
Console.WriteLine(myDelegate(5));
Func<int, bool> myFunc = x => x == 5;
Console.WriteLine(myFunc(4));
}
}
}