我是如何理解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

FuncAction是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号观察者
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

没事干写博客玩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值