2013年1月8日火曜日

What Is An Event In C#


using System;
 
namespace EventDemo
{
    //Event handler is a type of delegate like the following. Only the parameter type is different.
    public delegate void ChangeHandler(string oldnamestring newname);
 
    public class MySystem
    {
        // An event is a delegate of the event handler type.
        public event ChangeHandler OnChanged;
        private string _name = "Microsoft";
 
        public string Name
        {
            get { return _name; }
            set
            {
                if (_name == valuereturn;
                // The system fires up the event inside by calling the delegates.
                // However the system does not care what is delegated.
                OnChanged(_namevalue);
                _name = value;
            }
        }
    }
 
    internal class Program
    {
        private static void Main(string[] args)
        {
            var sample = new MySystem();
            // We tell the system what the event should delegate. 
            sample.OnChanged += sample_OnChanged;
            // And we "accidentally" makes an event happens.
            sample.Name = "Google";
            Console.ReadLine();
        }
 
        // Only we know what to is the event delegated.
        private static void sample_OnChanged(string senderstring e)
        {
            Console.WriteLine("Name changed!");
        }
    }
}

0 件のコメント:

コメントを投稿