匿名函数
匿名函数就是没有名字的函数,基于委托和事件
语法:delegate(参数列表)
{
//逻辑
};
使用范围:
1.函数中传递委托参数时
2.委托或事件赋值时
具体代码:
class Program
{
static void Main(string[] args)
{
//无参无返回值
Action action = delegate ()
{
Console.WriteLine("匿名函数逻辑");
};
action += f;
action();
//有参无返回值
Action<int,string> a2 = delegate (int a,string s)
{
Console.WriteLine(a + " " + s);
};
a2(1, "abc");
//有返回值
Func<int, string> f3 = delegate (int a)
{
return "zxc";
};
Console.WriteLine(f3(1));
//匿名函数参数传递
Test t = new Test();
t.f1(100, delegate ()
{
Console.WriteLine("匿名函数参数传递");
});
//匿名函数作为返回值
Action ac2 = t.GetFunc();
ac2();
//一步到位
t.GetFunc()();
Console.ReadKey();
}
static void f()
{
Console.WriteLine("1");
}
}
class Test
{
public Action action;
//参数传递
public void f1(int a,Action fun)
{
Console.WriteLine(a);
fun();
}
//作为返回值
public Action GetFunc()
{
return delegate ()
{
Console.WriteLine("匿名函数作为返回值");
};
}
}
匿名函数的缺点:函数没有名字,就无法从委托容器中移除
lambad表达式
lambad表达式就是匿名函数的简写,就声明不一样,其他用法一致
语法:
(参数列表)=>
{
//逻辑
};
因为用法一致,只给出不一样的地方:
//参数类型可以省略
Action<int> a3 = (value) =>
{
Console.WriteLine(value);
};
a3(50);
参数类型省略,偷懒罢了
闭包
闭包就是内层函数可以引用外层函数的变量,即使外出函数已经停止,也就是改变了变量的生命周期。
以下例子说明:
class Test
{
public event Action action;
public Test()
{
int value = 10;
action += () =>
{
Console.WriteLine("value:" + value);
};
}
public void p()
{
action();
}
}
class Program
{
static void Main(string[] args)
{
Test t = new Test();
t.p();
Console.ReadKey();
}
}
只要action没有置空,value就一致存在
注意:该变量的值不是创建时的值,而是父类最终时的值
以下例子说明:
for(int i=0;i<10;i++)
{
action += () =>
{
Console.WriteLine(i);
};
}
现象:
如果想要获取0-9,在for循环里创建临时变量存即可,这样每一层的临时变量就没有关系了