简体   繁体   中英

Passing Delegates to Events c#

Reading event description and examples of msdn I can see a discrepancy in the way events are subscribed to. Sometimes event handlers are passed "as is" and other times they are passed by instantiating a delegate using the handler method eg

...
class Subscriber
    {
        private string id;
        public Subscriber(string ID, Publisher pub)
        {
            id = ID;
            // Subscribe to the event using C# 2.0 syntax
            pub.RaiseCustomEvent += HandleCustomEvent;
        }

        // Define what actions to take when the event is raised. 
        void HandleCustomEvent(object sender, CustomEventArgs e)
        {
            Console.WriteLine(id + " received this message: {0}", e.Message);
        }
    } 

vs

public delegate void EventHandler1(int i);
...
public class TestClass
{
    public static void Delegate1Method(int i)
    {
        System.Console.WriteLine(i);
    }

    public static void Delegate2Method(string s)
    {
        System.Console.WriteLine(s);
    }
    static void Main()
    {
        PropertyEventsSample p = new PropertyEventsSample();

        p.Event1 += new EventHandler1(TestClass.Delegate1Method);
        p.RaiseEvent1(2);
       ...
     }
}

Can someone please provide clarity on this?

Thanks.

Your first code sample is syntactic sugar for the second one.
This syntax (omitting the constructor) was introduced by C# 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM