C# 委托、事件、Func、Action
委托:
在 .NET 中委托提供后期绑定机制。 后期绑定意味着调用方在你所创建的算法中至少提供一个方法来实现算法的一部分,它允许将方法作为参数传递给其他方法
可以把委托想象成一个合同,规定了方法的签名(比如方法的参数类型和返回值)。这个合同允许你将一个符合这个签名的方法绑定到委托上。当委托被调用时,它就会执行绑定的方法
string a, b, x;
static int CWStr(int s)
{
return s;
}
static int Add(int a)
{
return a + 10;
}
static int DoSomeSthing(MyDelegate myD)
{
myD += Add;
return myD(100);
}
MyDelegate myD = null;
myD += Add;
a = myD(10) + "";
myD = CWStr;
b = $"This Is Console Word:{myD(20)}";
x = DoSomeSthing(myD) + "";
Console.WriteLine($"{a},\r\n{b},\r\n{x}");
Console.ReadKey();
public delegate int MyDelegate(int a);
在委托delegate出现了很久以后,微软的.NET设计者们终于领悟到,其实所有的委托定义都可以归纳并简化成只用Func与Action这两个语法糖来表示。
其中,Func代表有返回值的委托,Action代表无返回值的委托。有了它们两,我们以后就不再需要用关键字delegate来定义委托了。
string a, b, x;
static int CWStr(int s)
{
return s;
}
static int Add(int a)
{
return a + 10;
}
static int DoSomeSthing(Func<int,int> myD)
{
myD = Add;
return myD(100);
}
Func<int,int> myD = null;
myD += Add;
a = myD(10) + "";
myD = CWStr;
b = $"This Is Console Word:{myD(20)}";
x = DoSomeSthing(myD) + "";
Console.WriteLine($"{a},\r\n{b},\r\n{x}");
Console.ReadKey();
事件
事件是一种特殊的委托,且只能用+=或-=
事件是对象用于(向系统中的所有相关组件)广播已发生事情的一种方式。 任何其他组件都可以订阅事件,并在事件引发时得到通知,它允许一个对象将状态的变化通知其他对象,而不需要知道这些对象的细节
可以把它理解为一个通知系统:一个对象(事件的“发布者”)发布事件,其他对象(事件的“订阅者”)可以订阅这个事件,收到通知后做出反应。
Cat cat = new Cat();
new People(cat);
new Mouse(cat);
cat.DoSomting();
public delegate void ActionHandler();
class Cat
{
public event ActionHandler Action;
public void DoSomting()
{
Console.WriteLine("猫叫了一声");
Action?.Invoke();
}
}
class People
{
public People(Cat cat)
{
cat.Action += () =>
{
Console.WriteLine("人醒了");
};
}
}
class Mouse
{
public Mouse(Cat cat)
{
cat.Action += () =>
{
Console.WriteLine("老鼠跑了");
};
}
}

浙公网安备 33010602011771号