什麼是委託:
1-委託是一個類
2-委託是一個特殊的類,他不是反映客觀事件的抽象,而是一種包裹着方法,通過委託類型的實例來間接的調用一些方法
下面是一個委託的基本例子
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
MyDele dele1 = new MyDele(M1);
dele1.Invoke();
}
static void M1()
{
Console.WriteLine("M1 is called");
}
}
delegate void MyDele();
}
MyDele裏包裹了M1的方法來交給dele1,然後dele1.invoke()調用
泛型委託
下面是一個泛型委託的例子
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
MyDele<int> deleAdd = new MyDele<int>(Add);
deleAdd(100, 200);
MyDele<double> deleMul = new MyDele<double>(Mul);
deleMul(200, 300);
}
static int Add(int a , int b)
{
return a + b;
}
static double Mul(double a , double b)
{
return a * b;
}
}
delegate T MyDele<T>(T a, T b);
}
使用泛型委託,可以減少委託定義的次數,對於同一種類似的委託,只需要定義一種泛型委託,就可以實現函數的包裹
實際開發中,微軟的.net框架已經爲我們準備好了帶返回值和不帶返回值的委託。func 和 action
下面的例子是對上面例子的改寫
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
Action action = new Action(M1);
action();
Action<string> action1 = new Action<string>(SayHello);
action1("Tim");
Func<int, int, int> func1 = new Func<int, int, int>(Add);
int res= func1(100, 100);
Console.WriteLine(res);
}
static void M1()
{
Console.WriteLine("M1 is called");
}
static void SayHello(string name)
{
Console.WriteLine($"Hello,{name}!");
}
static int Add(int a , int b)
{
return a + b;
}
static double Mul(double a , double b)
{
return a * b;
}
}
}
Lambda表達式
一種inline的匿名方法
調用的時候纔去聲明的纔是inline方法
下面就是使用Lambda表達式的例子,例子中使用的就是inline方法,使用的時候聲明,這樣的代碼顯得不那麼臃腫
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Func<int, int, int> func = new Func<int, int, int>((int a, int b) => { return a + b; });
int res = func(100, 200);
Console.WriteLine(res);
func = new Func<int, int, int>((int a, int b) => { return a * b; });
Console.WriteLine(func(100,200));
}
}
}
下面是Lambda表達式的簡寫
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Func<int, int, int> func = ( a, b) => { return a + b; };
int res = func(100, 200);
Console.WriteLine(res);
func = ( a, b) => { return a * b; };
Console.WriteLine(func(100,200));
}
}
}
泛型方法+泛型委託類型參數+泛型參數+Lambda表達式作爲參數的實例
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
DoSomeCal<int>(( a, b) => { return a + b; }, 100, 200);
}
static void DoSomeCal<T>(Func<T,T,T> func ,T x, T y)
{
T res = func(x, y);
Console.WriteLine(res);
}
}
}
LINQ
後面補充