事件

作者:追风剑情 发布于:2021-1-12 16:07 分类:C#

示例一:自定义事件类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp16
{
    class Program
    {
        //EventHandler已在System命名空间中定义,这里直接使用。
        public event EventHandler RaiseEvent;
        //使用EventHandler的泛型版本,发布自定义事件参数。
        public event EventHandler<CustomEventArgs> RaiseCustomEvent1;
        //直接声明自定义事件与上面的泛型版本等价
        public event CustomEventHandler RaiseCustomEvent2;

        static void Main(string[] args)
        {
            var pub = new Publisher();
            var sub1 = new Subscriber("sub1", pub);
            var sub2 = new Subscriber("sub2", pub);
            pub.DoSomething();
            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
        }

        //事件发布者
        public class Publisher
        {
            public event EventHandler<CustomEventArgs> RaiseCustomEvent;

            public void DoSomething()
            {
                OnRaiseCustomEvent(new CustomEventArgs("Event triggered"));
            }

            protected virtual void OnRaiseCustomEvent(CustomEventArgs e)
            {
                EventHandler<CustomEventArgs> raiseEvent = RaiseCustomEvent;
                if (raiseEvent != null)
                {
                    e.Message += $" at {DateTime.Now}";
                    //raiseEvent(this, e);
                    //防止raiseEvent为null,可以这样写。
                    raiseEvent?.Invoke(this, e);
                }
            }
        }

        //事件订阅者
        public class Subscriber
        {
            private readonly string _id;

            public Subscriber(string id, Publisher pub)
            {
                _id = id;
                pub.RaiseCustomEvent += HandleCustomEvent;
            }

            void HandleCustomEvent(object sender, CustomEventArgs e)
            {
                Console.WriteLine($"{_id} received this message: {e.Message}");
            }
        }
    }

    //自定义事件数据类
    public class CustomEventArgs : EventArgs
    {
        public string Message { get; set; }

        public CustomEventArgs(string message)
        {
            Message = message;
        }
    }

    //事件是特殊类型的委托
    public delegate void CustomEventHandler(object sender, CustomEventArgs args);
}

运行测试
1111.png

示例二:接口事件与事件访问器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp16
{
    class Program
    {
        static void Main(string[] args)
        {
            Shape shape = new Shape();
            Subscriber1 sub1 = new Subscriber1(shape);
            Subscriber2 sub2 = new Subscriber2(shape);
            shape.Draw();
            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
        }

        public interface IDrawingObject
        {
            event EventHandler OnDraw;
        }

        public interface IShape
        {
            event EventHandler OnDraw;
        }

        public class Shape : IDrawingObject, IShape
        {
            event EventHandler PreDrawEvent;
            event EventHandler PostDrawEvent;

            object objectLock = new object();

            //通过提供自己的访问器,可以指定两个事件是由类中的同一个事件表示,还是由不同事件表示。
            event EventHandler IDrawingObject.OnDraw
            {
                add
                {
                    lock (objectLock)
                    {
                        PreDrawEvent += value;
                    }
                }
                remove
                {
                    lock (objectLock)
                    {
                        PreDrawEvent -= value;
                    }
                }
            }

            event EventHandler IShape.OnDraw
            {
                add
                {
                    lock (objectLock)
                    {
                        PostDrawEvent += value;
                    }
                }
                remove
                {
                    lock (objectLock)
                    {
                        PostDrawEvent -= value;
                    }
                }
            }

            public void Draw()
            {
                PreDrawEvent?.Invoke(this, EventArgs.Empty);
                Console.WriteLine("Drawing a shape.");
                PostDrawEvent?.Invoke(this, EventArgs.Empty);
            }
        }

        //订阅者1
        public class Subscriber1
        {
            public Subscriber1(Shape shape)
            {
                IDrawingObject d = (IDrawingObject)shape;
                d.OnDraw += d_OnDraw;
            }

            void d_OnDraw(object sender, EventArgs e)
            {
                Console.WriteLine("Sub1 receives the IDrawingObject event.");
            }
        }

        //订阅者2
        public class Subscriber2
        {
            public Subscriber2(Shape shape)
            {
                IShape d = (IShape)shape;
                d.OnDraw += d_OnDraw;
            }

            void d_OnDraw(object sender, EventArgs e)
            {
                Console.WriteLine("Sub2 receives the IShape event.");
            }
        }
    }
}

运行测试
22222.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号