我是如何理解delegate和event的
引言
在以前我学习C#时,有一天看到了delegate
,发现这玩意挺好用,和函数指针一样,之后又出来了个event
,我当时真的没明白为什么需要这个event
,有点画蛇添足。
delegate
delegate
英文直译委托
,理解它其实很简单,在理解它之前,我们看看如何使用它。
声明委托
首先我们需要声明
一个委托
。
声明委托
其实和声明函数
是一样的,唯一的区别在于前面多了个delegate
关键字(虽然C#里没法单纯的声明函数)。
学过C的小伙伴可以把它当做一个函数指针声明。
delegate void MyDelegate(string str);
使用委托
我们使用类创建对象的时候是 类名 变量名 = new 类名
。
使用委托时也是一样,不过它和C#中对类创建对象不同,它具有显式
和隐式
两种方式使用。
using System;
namespace Example
{
class Program
{
//声明一个委托
delegate void MyDelegate(string str);
static void TestFunc(string str)
{
Console.WriteLine(str);
}
static void Main(string[] args)
{
string str = "Hello";
//显式定义委托
MyDelegate explicitDelegate = new MyDelegate(TestFunc);
explicitDelegate(str);
//隐式定义委托
MyDelegate implicitDelegate = TestFunc;
str = "Hi";
implicitDelegate(str);
}
}
}
上面的栗子会输出:
Hello
Hi
添加新的Function
你以为它只能充当函数指针
或者匿名函数
的功能那可就错了,它可以不停的加入新的Function(也可以移除)
,这玩意还能这样用:
using System;
namespace Example
{
class Program
{
delegate void MyDelegate(string str);
static void TestFunc(string str)
{
Console.WriteLine(str);
}
static void TestFunc2(string str)
{
Console.WriteLine("{0} 我是2号",str);
}
static void Main(string[] args)
{
string str = "Hello";
MyDelegate implicitDelegate = TestFunc;
implicitDelegate += TestFunc2;
explicitDelegate(str);
}
}
}
上面的栗子会输出:
Hello
Hello 我是2号
Func和Action
Func
和Action
是C#中声明好的泛型委托
,为了我们使用方便。其定义如下:
public delegate TResult Func<in T, out TResult>(T arg);
//以此类推
public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
public delegate void Action<in T>(T obj);
//以此类推
public delegate void Action<in T1, in T2>(T1 arg1, T2 arg2);
可以看见Func
其实就是带返回值
得委托,Action
是无返回值
的委托。
使用栗子:
using System;
namespace Example
{
class Program
{
static string MyFunction(int i) {
return i.ToString();
}
static void MyAction(string str)
{
Console.WriteLine("传给我的是{0}",str);
}
static void Main(string[] args)
{
Func<int, string> myFunc = MyFunction;
Action<string> myAction = MyAction;
string str = myFunc(10);
myAction(str);
}
}
}
上面的栗子会输出:
传给我的是10
委托异步方式
委托
还可以异步运行
,但是需要注意:异步
运行委托只能有一个目标
,不能+=
添加多个目标。
使用:
using System;
namespace Example
{
class Program
{
//声明一个委托
delegate string MyDelegate(string str);
static string TestFunc(string str)
{
return "哈喽 " + str;
}
static void Main(string[] args) {
//显式定义委托
MyDelegate myDelegate = new MyDelegate(TestFunc);
IAsyncResult asyncResult = myDelegate.BeginInvoke("Hello", null, null);
/*
* 一直阻塞到可以获取结果
while (!asyncResult.IsCompleted);
string res = myDelegate.EndInvoke(asyncResult);// 取回结果
Console.WriteLine(res);
*/
// 只等待1000毫秒
if (asyncResult.AsyncWaitHandle.WaitOne(1000))
{
string res = myDelegate.EndInvoke(asyncResult); // 取回结果
Console.WriteLine(res);
}
}
}
}
使用回调函数
using System;
namespace Example
{
class Program
{
static string TestFunc(string str)
{
return "哈喽 " + str;
}
static void OnCallback(IAsyncResult res)
{
// 把IAsyncResult.AsyncState 存放着我们传进来的第三个参数
// 也就是委托本身 需要类型转换
Func<string, string> myDelegate = res.AsyncState as Func<string, string>;
string Res = myDelegate.EndInvoke(res); // 取回结果
Console.WriteLine("线程结束 " + Res);
}
static void Main(string[] args) {
Func<string,string> myDelegate = TestFunc;
//第二个参数是回调函数,第三个参数可以在回调函数中通过IAsyncResult.AsyncState取出,一般我们会传委托本身,这样取结果的动作我们在回调函数中就可以完成
IAsyncResult asyncResult = myDelegate.BeginInvoke("Hello", OnCallback, myDelegate);
//避免主线程结束
while (!asyncResult.IsCompleted);
}
}
}
event
当时看到event
时,我觉得这是个画蛇添足的东西,因为单纯的delegate
已经能用,为什么要用event delegate
?
使用
event
是为了封装性
,让其在外部只能添加或移除
,但是无法在类外直接调用
,仅仅就是这个作用而已。
using System;
namespace Example
{
//命名空间下声明了一个委托为ObserverDelegate
delegate void ObserverDelegate(string str);
class Observable {
//其实notifyObservers成员只是前面多了个event关键字
public event ObserverDelegate notifyObservers;
//这样使用也是可以的
//public event Action<string> notifyObservers;
public void NotifyAll() {
//类中可以直接调用
notifyObservers("哈喽");
}
}
class Observer
{
private string name;
public Observer(string name) {
this.name = name;
}
public void Notify(string str) {
Console.WriteLine("{0} {1}", str, this.name);
}
}
}
使用:
namespace Example
{
class Program
{
static void Main(string[] args)
{
Observable observable = new Observable();
//observable.notifyObservers = new Observer("1号观察者").Notify; //报错 虽然是public 但无法使用除了+=和-=之外的任何方式
observable.notifyObservers += new Observer("1号观察者").Notify;
observable.notifyObservers += new Observer("2号观察者").Notify;
observable.notifyObservers += new Observer("3号观察者").Notify;
observable.notifyObservers += new Observer("4号观察者").Notify;
observable.notifyObservers += new Observer("5号观察者").Notify;
//observable.notifyObservers("哈喽"); //报错 虽然是public 但无法在类外调用
observable.NotifyAll();
}
}
}
上面的栗子会输出:
哈喽 1号观察者
哈喽 2号观察者
哈喽 3号观察者
哈喽 4号观察者
哈喽 5号观察者