event Action<> vs event EventHandler<>

后端 未结 7 2205
野的像风
野的像风 2020-11-28 02:05

Is there any different between declaring event Action<> and event EventHandler<>.

Assuming it doesn\'t matter what object actua

7条回答
  •  时光取名叫无心
    2020-11-28 02:25

    If you follow the standard event pattern, then you can add an extension method to make the checking of event firing safer/easier. (i.e. the following code adds an extension method called SafeFire() which does the null check, as well as (obviously) copying the event into a separate variable to be safe from the usual null race-condition that can affect events.)

    (Although I am in kind of two minds whether you should be using extension methods on null objects...)

    public static class EventFirer
    {
        public static void SafeFire(this EventHandler theEvent, object obj, TEventArgs theEventArgs)
            where TEventArgs : EventArgs
        {
            if (theEvent != null)
                theEvent(obj, theEventArgs);
        }
    }
    
    class MyEventArgs : EventArgs
    {
        // Blah, blah, blah...
    }
    
    class UseSafeEventFirer
    {
        event EventHandler MyEvent;
    
        void DemoSafeFire()
        {
            MyEvent.SafeFire(this, new MyEventArgs());
        }
    
        static void Main(string[] args)
        {
            var x = new UseSafeEventFirer();
    
            Console.WriteLine("Null:");
            x.DemoSafeFire();
    
            Console.WriteLine();
    
            x.MyEvent += delegate { Console.WriteLine("Hello, World!"); };
            Console.WriteLine("Not null:");
            x.DemoSafeFire();
        }
    }
    

提交回复
热议问题