前言:
之前讲委托是为了给事件讲,现在讲委托是为了给Lambda表达式讲,而讲Lambda表达式是为了讲LinQ。
委托
什么是委托
委托是一种类型,是一种类类型,是引用类型的一种。委托就是一个或一组方法的包装器。C、C++中用函数指针实现。声明委托为delegate。委托也可以叫做多播委托,一个委托可以包裹着好几个方法。
using System;
namespace ConsoleApp4
{
internal class Program
{
static void Main(string[] args)
{
MyDele dele1 = new MyDele(M1);//dele1这个变量引用着一个MyDele类型的实例,这个实例里“包裹”着M1这个方法
dele1 += (new Student()).SayHello;// 也可以包裹好几个方法
dele1();
}
static void M1()//静态方法
{
Console.WriteLine("M1 is called.");
}
}
class Student
{
public void SayHello()//实例方法
{
Console.WriteLine("Hello,I'm a student!");
}
}
delegate void MyDele();//委托声明
}
泛型委托
using System;
namespace ConsoleApp5
{
internal class Program
{
static void Main(string[] args)
{
MyDele<int> deleAdd = new MyDele<int>(Add);
int result1 = deleAdd(3, 4);
MyDele<double> deleMul = new MyDele<double>(Mul);
double result2 = deleMul(3.0, 4.5);
Console.WriteLine(result1);
Console.WriteLine(result2);
Console.WriteLine(deleAdd.GetType().IsClass);//委托类型是一种特殊的类类型
}
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为我们声明好的委托,无返回值用Action,有返回值用Func
using System;
namespace ConsoleApp5
{
internal class Program
{
static void Main(string[] args)
{
Action action = new Action(M1);
action.Invoke();
Action<string,int> action2 = new Action<string,int>(SayHello);
action2("Xiao Ming",4);
Func<int, int, int> action3 = new Func<int, int,int>(Add);
int res1 = action3(3, 4);
var action4 = new Func<double, double, double>(Mul);//var关键字缩短代码
double res2 = action4(3.0, 5.5);
}
static void M1()
{
Console.WriteLine("Ma is called");
}
static void SayHello(string name,int round)
{
for (int i = 0; i < round; i++)
{
Console.WriteLine($"Hello, {name}");
}
}
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);
}
}
Lambda表达式
Lambda就是InLine的匿名方法
作用:
- 匿名方法
- InLine方法:在调用时才去声明
另外,反正Lambda表达式求值完了得一委托类型的实例,所以可以干脆这么写:
泛型委托的类型参数推断
函数的形式参数也是一种变量,那么如果func1是一个函数的参数的话,那么当你在调用这个函数的时候,我是不是可以把一个Lambda表达式当做实参传进去,并且涉及到泛型委托的类型参数推断
using System;
namespace ConsoleApp5
{
internal class Program
{
static void Main(string[] args)
{
DoSomeCalc<int>(( a, b) => { return a * b; }, 100, 200);//其中这个<int>也可以去掉,因为100,200就能推断出来T类型是int,这就是泛型委托的类型推断
}
static void DoSomeCalc<T>(Func<T, T, T> func,T x,T y)
{
T res = func(x,y);
Console.WriteLine(res);
}
}
}
LinQ
LINQ:.NET Language Integrated Quary(查询 ),SQL(数据库语言),几乎所有关系型数据库都用C寇(SQL)。LINQ本身除了查询数据库以外,本地有个例子有个集合也可以来查询,只是一种查询的方式而已。在工作中,LINQ还是和数据库打交道(如果想更深入的了解LINQ可以看一下 LINQ 大揭秘系列 BV1rx41157DS)。现在要是想用LINQ查询数据库的话,.NET类库里面有两组功能语法都能让我们拿LINQ去查询数据库,一组叫LINQ to SQL,这个是一个比较小的类库,他集成在我们.NET FrameWork里边,但是它的功能并不是很强;另外一组的功能很强,但是是独立在.NET FrameWork平台之外的,叫做Entity Framework,简称EF,今天演示EF。
此示例需要SQL数据库前置,暂无涉及