lambda 表达式 (int x, int y) => { return x + y }
delegate 所引用的函数可以用匿名的方式定义
和 js 一样,lambda 表达式会捕捉定义时上下文中的变量,形成闭包。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace ConsoleApp1
{
class learn_lambda
{
delegate int Two(int a, int b);
static Two m = null;
static void Main()
{
m = new Two((int a, int b) => {
return a + b;
});
Console.WriteLine(m(1, 2)); // 3
int c = 1;
m = new Two((int a, int b) =>
{
return a + b + c;
});
Console.WriteLine(m(1, 2)); // 4
c = 2; // modify the value at &c
Console.WriteLine(m(1, 2)); // 5, proving that 'c' is calculated at runtime
Run2(); // 4
m = GetTwo();
Console.WriteLine(m(1, 2)); // 6
Console.ReadKey();
}
static void Run2()
{
int c = 2; // 毫无影响
Console.WriteLine(m(1, 2));
}
static Two GetTwo()
{
int c = 3;
return new Two((int a, int b) =>
{
return a + b + c; // c still exists even the stack for GetTwo is gone
});
}
}
}
lambda 表达式还可以这样写
(int a, int b) => a + b
例如
m = (int a, int b) => a + b; // making it more compact
var
var
有点像 C艹 里的 auto
,声明变量时可以用 var
作为替代具体的类型,编译器会推断具体类型。
var
的确定时刻是编译时。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace ConsoleApp1
{
class learn_var
{
class Shit
{
string component;
public Shit(string str)
{
this.component = str;
}
}
static void Main()
{
var a = 1;
var b = 1.0;
var shit = new Shit("nothing");
Console.WriteLine(a.GetType());
Console.WriteLine(b.GetType());
Console.WriteLine(shit.GetType());
Console.ReadKey();
}
}
}