c# event

Event declaration and implementation:

    // Declare event arguement class
    public class SampleEventArgs
    {
        public SampleEventArgs(string s) { Text = s; }
        public string Text { get; private set; }
    }

    // Declare a delegate to handler event
    public delegate void OnRequestRaisedHandler(object sender, SampleEventArgs args);

    // Declare a class with event member
    public class SampleEventClass
    {
        // Declare OnRequestRaised event, event type is delegate
        public event OnRequestRaisedHandler OnRequestRaised;

        public void ExecuteTask()
        {
            for (int i = 0; i < 10; i++)
            {
                // Trigger OnRequestRaised event when i is 9
                if (i == 9 && OnRequestRaised != null)
                {
                    OnRequestRaised(this, new SampleEventArgs("i is 9"));
                }
            }
        }
    }

Usage:

        public static void ProcessRequestRaised(object sender, SampleEventArgs args)
        {
            Console.WriteLine(string.Format("sender is: {0}", sender));
            Console.WriteLine(string.Format("argument is: {0}", args.Text));
        }

        public static void EventTask()
        {
            SampleEventClass instance = new SampleEventClass();
            // In c# version 1.0, below statement must use keyword new to add event handler, which should be:
            // instance.OnRequestRaised += new OnRequestRaisedHandler(ProcessRequestRaised);
            // In c# versioin 2.0 and onward, you can directly add the named method
            instance.OnRequestRaised += ProcessRequestRaised;
            instance.ExecuteTask();
        }

.NET framework has provided EventHandler delegate and EventArgs class, they are replace the OnRequestRaisedHandler and SampleEventArgs in the above sample.

posted @ 2017-04-29 16:09  liangzi4000  阅读(141)  评论(0编辑  收藏  举报