什么是委托:
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
后面补充