C#中的Lambda表达式与委托的比较及用法
Lambda表达式
"Lambda表达式"是一个匿名函数,是一种高效的类似于函数式编程的表达式,Lambda简化了开发中需要编写的代码量。它可以包含表达式和语句,并且可用于创建委托或表达式目录树类型,支持带有可绑定到委托或表达式树的输入参数的内联表达式。所有Lambda表达式都使用Lambda运算符=>,该运算符读作"goes to"。Lambda运算符的左边是输入参数(如果有),右边是表达式或语句块。Lambda表达式x => x * x读作"x goes to x times x"。可以将此表达式分配给委托类型
lambda表达式参数的输入:
1.0个参数:[]=>expr
2.一个参数:param=>expr
3.多个参数:(param-list)=>expr
例子
delegate int del(int i);
static void Main(string[] args)
{
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
}
Lambda表达式用法解析
委托:
delegate int del(int i);
static void Main(string[] args)
{
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
}
Lambda表达式
delegate int Test(int a);
static void Main(string[] args)
{
// Test gwl = JieZhang;
Test gwl = p => p + 10;
Console.WriteLine(gwl(10) + ""); //打印20,表达式的应用
Console.ReadKey();
}
多参数的Lambda表达式
delegate int Test(int a,int b);
static void Main(string[] args)
{
Test gwl = (p,z) => z-(p + 10);
Console.WriteLine(gwl(10,100) + ""); //打印80,z对应参数b,p对应参数a
Console.ReadKey();
}
以Lambda为主体的运算
delegate int Test(int a,int b);
static void Main(string[] args)
{
Test gwl = (p, z) =>
{
int zuidixiaofei = 10;
if (p < zuidixiaofei)
{
return 100;
}
else
{
return z - p - 10;
}
};
Console.WriteLine(gwl(10,100) + ""); //打印80,z对应参数b,p对应参数a
Console.ReadKey();
}
Func<T>委托
T 是参数类型,这是一个泛型类型的委托,用起来很方便的。
static void Main(string[] args)
{
Func<int, string> gwl = p => p + 10 + "--返回类型为string";
Console.WriteLine(gwl(10) + ""); //打印‘20--返回类型为string’,z对应参数b,p对应参数a
Console.ReadKey();
}
说明:我们可以看到,这里的p为int 类型参数, 然而lambda主体返回的是string类型的。
再上一个例子
static void Main(string[] args)
{
Func<int, int, bool> gwl = (p, j) =>
{
if (p + j == 10)
{
return true;
}
return false;
};
Console.WriteLine(gwl(5,5) + ""); //打印‘True’,z对应参数b,p对应参数a
Console.ReadKey();
}
说明:从这个例子,我们能看到,p为int类型,j为int类型,返回值为bool类型。
看完上面两个例子,相信大家应该明白啦Func<T>的用法:多个参数,前面的为委托方法的参数,最后一个参数,为委托方法的返回类型。
Lambda在C++ sort()排序函数中的应用
首先定义一个ListNode链表
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
如何定义链表按照首节点进行排序的规则呢
用cmp方法
vector<ListNode*>sList;
struct cmp
{
bool operator() (const ListNode* a, const ListNode* b)
{
return a->val > b->val;
}
};
sort(sList.begin(), sList.end() ,cmp);
Lambda表达式
sort(sList.begin(), sList.end() ,
[](const ListNode* a, const ListNode* b) { return a->val > b->val; });
网友评论