Lambda表达式
1. Lambda的Hello World
2. Lambda表达式
3. Lambda代码块
4. 不确定参数的Lambda表达式
5. Lambda表达式中变量作用域
6. 参考资料
7. 代码下载
1. Lambda的Hello World
delegate int del(int i);
// delegate hello world
del myDelegate = x => x * x;
int j = myDelegate(10);
上面代码首先声明一个代理del,然后在对del进行赋值是采用的是Lambda表达式的形式,通过赋值,del就能够表示输入x,返回x的平凡。

2. Lambda表达式
简单的将Lambda就是在=>之后跟着的是一个表达式,上面的Hello World程序中就是Lambda表达式。另外的示例:
(int x, string s) => s.Length > x
3. Lambda代码块
TestTheSame testTheSame =
(x, y) =>
{
return (x == y);
};
4. 不确定参数的Lambda表达式Func<T, TResult>
通过使用Func<T, TResult>能够实现不确定参数的delegate,示例:
delegate TResult Func<TArg, TResult>(TArg arg);
Func<int, bool> myFunc1 =
x => x == 5;
Console.WriteLine(myFunc1(5)); // true
// 这里是两个输入参数
Func<int, int, int> myFunc2 =
(x, y) => x + y;
Console.WriteLine(myFunc2(1, 2)); // 3
5. Lambda表达式中变量作用域
在Lambda表达式内部是能够改变全局变量的。msdn上的示例:
delegate bool D();
delegate bool D2(int i);
class Test
{
D del;
D2 del2;
public void TestMethod(int input)
{
int j = 0;
// Initialize the delegates with lambda expressions.
// Note access to 2 outer variables.
// del will be invoked within this method.
del = () => { j = 10; return j > input; };
// del2 will be invoked after TestMethod goes out of scope.
del2 = (x) => {return x == j; };
// Demonstrate value of j:
// Output: j = 0
// The delegate has not been invoked yet.
Console.WriteLine("j = {0}", j); // Invoke the delegate.
bool boolResult = del();
// Output: j = 10 b = True
Console.WriteLine("j = {0}. b = {1}", j, boolResult);
}
static void Main()
{
Test test = new Test();
test.TestMethod(5);
// Prove that del2 still has a copy of
// local variable j from TestMethod.
bool result = test.del2(10);
// Output: True
Console.WriteLine(result);
Console.ReadKey();
}
}
6. 参考资料
http://msdn.microsoft.com/en-us/library/bb397687.aspx
http://msdn.microsoft.com/en-us/library/orm-9780596516109-03-09.aspx
7. 代码下载
/Files/xuqiang/csharp/Program.rar
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?