Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            var classWithMethodsMatchingEventTypes = new ClassWithMethodsMatchingEventTypes();

            // 1. Demonstrate how do "add" and "remove" accessors of event property work.
            var p = new Program();

            p.MyEvent += new EventHandler(classWithMethodsMatchingEventTypes.DoNothing);
            p.MyEvent -= null; // It does not matter that we are passing null, "remove" accessor code is executed.

            // 2. Attach the handler to an event declared using "shorthand" notation.
            var classWithTheShorthandEventProp = new ShorthandEventAndBackingDelegateDeclaration();

            classWithTheShorthandEventProp.NewMessage += new EventHandler <NewMessageEventArgs>
                                                             (classWithMethodsMatchingEventTypes.LogEventToConsole);
            NewMessageEventArgs eventArgs = new NewMessageEventArgs {
                Message = "Hello! It's a brand new message"
            };

            // Raise the event.
            classWithTheShorthandEventProp.OnNewMessage(eventArgs);
        }
Ejemplo n.º 2
0
        // The above is translated to the following in C# 1.1:
        // private EventHandler<NewMessageEventArgs> _newMessage;
        //
        // public event EventHandler<NewMessageEventArgs> NewMessage
        // {
        //      add
        //      {
        //          lock (this)
        //          {
        //              _newMessage += value;
        //          }
        //      }
        //      remove
        //      {
        //          lock (this)
        //          {
        //              _newMessage -= value;
        //          }
        //      }
        //  }

        /// <summary>
        /// Raises the NewMessage event.
        /// </summary>
        public virtual void OnNewMessage(NewMessageEventArgs e)
        {
            NewMessage?.Invoke(this, e);
        }
Ejemplo n.º 3
0
 public void LogEventToConsole(object sender, NewMessageEventArgs e)
 {
     Console.WriteLine(e.Message);
 }