C#中的delegate类似于C++中的模板函数,都是将方法像一些常规变量那样传递与使用。
且lambda都类似于匿名函数一样,来回折腾。
event和delegate的区别后面贴出。
贴点代码。
public class MyTest
{
public delegate string GetString();
static void Main(String[] args)
{
int x = 20;
//将方法名传入构造函数的思路
GetString getString = new GetString(x.ToString);
Console.WriteLine(getString().GetType());
getString = () => "测试lambda和delegate函数";
Console.WriteLine(getString());
Console.WriteLine("-------------------------------------\n");
//Action是系统提供的无返回值的代理
Action<int> action = i => Console.WriteLine("参数为:" + i);
action(20);
Console.WriteLine("-------------------------------------\n");
//Func是系统提供的带一个返回值的代理
Func<string, int> func = s => int.Parse(s);
Console.WriteLine("该方法的返回值为:" + func("30"));
Console.WriteLine("-------------------------------------\n");
//多播委托也是很有用的一个策略,使用+=与-=来控制注册与取消
Action testMultyDelegate = () => Console.WriteLine("第一个方法");
testMultyDelegate += () => Console.WriteLine("第二个方法");
Delegate[] delegates = testMultyDelegate.GetInvocationList();
foreach (var @delegate in delegates)
{
@delegate.DynamicInvoke();
}
Console.WriteLine("-------------------------------------\n");
//lambda表达式的注意事项。
//如果是一个参数,则可以直接写参数名,不用带括号,且不用带数据类型。
//如果方法体内只有一条语句,可以不写花括号和return,系统会背后添加。
//lambda可以访问外部变量,但不建议这样做,容易出现问题。
Console.ReadKey();
}
}
-事件是一种特殊的委托,或者说是受限制的委托,是委托一种特殊应用,只能施加+=,-=操作符。二者本质上是一个东西。
-event ActionHandler Tick; // 编译成创建一个私有的委托示例, 和施加在其上的add, remove方法.
-event只允许用add, remove方法来操作,这导致了它不允许在类的外部被直接触发,只能在类的内部适合的时机触发。委托可以在外部被触发,但是别这么用。
-使用中,委托常用来表达回调,事件表达外发的接口。
本文深入探讨了C#中的Delegate和Lambda表达式的基本概念及其使用方式,包括如何定义和使用Delegate,Lambda表达式的语法特点及注意事项,并通过具体示例展示了它们在实际编程中的应用。

1680

被折叠的 条评论
为什么被折叠?



