Csharp/CSharp Tutorial/delegate/delegate event

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Advanced Event

using System;
using System.Collections.Generic;
using System.Text;
delegate void NameChangedDelegate(string name, string newValue);
class Program
{
    static void Main(string[] args)
    {
        Employee c = new Employee();
        Subscriber s1 = new Subscriber(c, "subscriber-A");
        Subscriber s2 = new Subscriber(c, "subscriber-B");
        Subscriber s3 = new Subscriber(c, "subscriber-C");
        c.FirstName = "F";
        s2.Unsubscribe();
        c.FirstName = "A";
    }
}
class Subscriber
{
    public string SubscriberID = "new subscriber";
    public Employee myEmployee = null;
    public NameChangedDelegate ncDel = null;
    public Subscriber(Employee c, string subId)
    {
        SubscriberID = subId;
        ncDel = new NameChangedDelegate(myEmployee_OnNameChanged);
        myEmployee = c;
        myEmployee.OnNameChanged += ncDel;
    }
    void myEmployee_OnNameChanged(string name, string newValue)
    {
        Console.WriteLine("[{0}] Employee {1} changed to {2}.", SubscriberID,
            name, newValue);
    }
    public void Unsubscribe()
    {
        myEmployee.OnNameChanged -= ncDel;
    }
}
class Employee
{
    private string firstName;
    private event NameChangedDelegate onNameChange;
    public event NameChangedDelegate OnNameChanged
    {
        add
        {
            onNameChange += value;
            if (value.Target is Subscriber)
            {
                Console.WriteLine("Subscriber "{0}" just subscribed to OnNameChanged.",
                    ((Subscriber)value.Target).SubscriberID);
            }
        }
        remove
        {
            onNameChange -= value;
            if (value.Target is Subscriber)
            {
                Console.WriteLine("Subscriber "{0}" just un-subscribed from OnNameChanged.",
                    ((Subscriber)value.Target).SubscriberID);
            }
        }
    }
    public string FirstName
    {
        get { return firstName; }
        set
        {
            firstName = value;
            onNameChange("firstname", value);
        }
    }
}

An event multicast demonstration

using System; 
 
delegate void MyEventHandler(); 
 
class MyEvent { 
  public event MyEventHandler SomeEvent; 
 
  public void OnSomeEvent() { 
    if(SomeEvent != null) 
      SomeEvent(); 
  } 
} 
 
class MouseEvent { 
  public void MouseEventHandler() { 
    Console.WriteLine("Event received by MouseEventHandler object"); 
  } 
} 
 
class KeyEvent { 
  public void KeyEventHandler() { 
    Console.WriteLine("Event received by KeyEventHandler object"); 
  } 
} 
 
class MainClass { 
  static void handler() { 
    Console.WriteLine("Event received by EventDemo"); 
  } 
 
  public static void Main() {  
    MyEvent evt = new MyEvent(); 
    MouseEvent xOb = new MouseEvent(); 
    KeyEvent yOb = new KeyEvent(); 
 
    evt.SomeEvent += handler; 
    evt.SomeEvent += xOb.MouseEventHandler; 
    evt.SomeEvent += yOb.KeyEventHandler; 
 
    evt.OnSomeEvent(); 
    Console.WriteLine(); 
 
    evt.SomeEvent -= xOb.MouseEventHandler; 
    evt.OnSomeEvent(); 
  } 
}
Event received by EventDemo
Event received by MouseEventHandler object
Event received by KeyEventHandler object
Event received by EventDemo
Event received by KeyEventHandler object

A static method is used as an event handler

using System; 
 
delegate void MyEventHandler(); 
 
class MyEvent { 
  public event MyEventHandler SomeEvent; 
 
  public void OnSomeEvent() { 
    if(SomeEvent != null) 
      SomeEvent(); 
  } 
} 
 
class KeyEvent { 
 
  public static void KeyEventHandler() { 
    Console.WriteLine("Event received by class."); 
  } 
} 
 
class MainClass { 
  public static void Main() {  
    MyEvent evt = new MyEvent(); 
 
    evt.SomeEvent += KeyEvent.KeyEventHandler; 
 
    evt.OnSomeEvent(); 
  } 
}
Event received by class.

A very simple event demonstration.

using System; 
 
delegate void MyEventHandler(); 
 
class MyEvent { 
  public event MyEventHandler SomeEvent; 
 
  public void OnSomeEvent() { 
    if(SomeEvent != null) 
      SomeEvent(); 
  } 
} 
 
class MainClass { 
  static void handler() { 
    Console.WriteLine("Event occurred"); 
  } 
 
  public static void Main() {  
    MyEvent evt = new MyEvent(); 
 
    evt.SomeEvent += handler; 
 
    evt.OnSomeEvent(); 
  } 
}
Event occurred

Creating an event.

using System;
public delegate void AgeChangeHandler(int age, object obj,
        ref bool dontdoit);
class Employee {
    public event AgeChangeHandler AgeChange;
    int fAge;
    public int Age {
        set {
            Boolean dontdoit = false;
            AgeChange(value, this, ref dontdoit);
            if (!dontdoit)
                fAge = value;
        }
        get {
            return fAge;
        }
    }
    public Employee() {
        fAge = 0;
    }
}
class MainClass {
    private static void MyAgeChangeHandler(int age, object obj,
          ref bool dontdoit) {
        Console.WriteLine(
           "MyAgeChangeHandler called with age {0} obj.age = {1}",
              age, ((Employee)obj).Age);
        if (age < 0 || age > 99)
            dontdoit = true;
    }
    public static void Main() {
        Employee p = new Employee();
        // Set up our handler
        p.AgeChange += new AgeChangeHandler(MyAgeChangeHandler);
        p.Age = 21;
        p.Age = 33;
    }
}

Creating a new event.

using System;
public class EventTestClass {
    private int nValue;
    public delegate void ValueChangedEventHandler();
    public event ValueChangedEventHandler Changed;
    protected virtual void OnChanged() {
        if (Changed != null)
            Changed();
        else
            Console.WriteLine("Event fired. No handler!");
    }
    public EventTestClass(int nValue) {
        SetValue(nValue);
    }
    public void SetValue(int nV) {
        if (nValue != nV) {
            nValue = nV;
            OnChanged();
        }
    }
}
public class MainClass {
    public static void Main() {
        EventTestClass etc = new EventTestClass(3);
        etc.SetValue(5);
        etc.SetValue(5);
        etc.SetValue(3);
    }
}

delegate and event

using System;
public delegate void EventHandler(int i);
class MainClass
{
  static void Main(string[] args)
  {
    MyEventPublisher EventPublisher = new MyEventPublisher();
    
    EventHandler MyAnonymousDelegate = delegate(int x)
    {
      Console.WriteLine("Anonymous Event FIRED!");
    };
    EventPublisher.MyEvent += MyAnonymousDelegate;
    
    EventPublisher.DoSomething();
  }
  
}
public class MyEventPublisher
{
  public event EventHandler MyEvent;
  public int DoSomething()
  {
    MyEvent(5);
    return 0;
  }
}
Anonymous Event FIRED!

Individual objects receive notifications when instance event handlers are used

using System; 
 
delegate void MyEventHandler(); 
 
class MyEvent { 
  public event MyEventHandler SomeEvent; 
 
  public void OnSomeEvent() { 
    if(SomeEvent != null) 
      SomeEvent(); 
  } 
} 
 
class KeyEvent { 
  int id; 
 
  public KeyEvent(int x) { 
     id = x; 
  } 
 
  public void KeyEventHandler() { 
    Console.WriteLine("Event received by object " + id); 
  } 
} 
 
class MainClass { 
  public static void Main() {  
    MyEvent evt = new MyEvent(); 
    KeyEvent o1 = new KeyEvent(1); 
    KeyEvent o2 = new KeyEvent(2); 
    KeyEvent o3 = new KeyEvent(3); 
 
    evt.SomeEvent += o1.KeyEventHandler; 
    evt.SomeEvent += o2.KeyEventHandler; 
    evt.SomeEvent += o3.KeyEventHandler; 
 
    evt.OnSomeEvent(); 
  } 
}
Event received by object 1
Event received by object 2
Event received by object 3

Retrieving Even-Numbered Events

using System;
   
public delegate void EvenNumberHandler(int Number);
   
class Counter
{
    public event EvenNumberHandler OnEvenNumber;
   
    public Counter()
    {
        OnEvenNumber = null;
    }
   
    public void CountTo100()
    {
        int CurrentNumber;
   
        for(CurrentNumber = 0; CurrentNumber <= 100; CurrentNumber++)
        {
            if(CurrentNumber % 2 == 0)
            {
                if(OnEvenNumber != null)
                {
                    OnEvenNumber(CurrentNumber);
                }
            }
        }
    }
}
   
class EvenNumberHandlerClass
{
    public void EvenNumberFound(int EvenNumber)
    {
        Console.WriteLine(EvenNumber);
    }
}
   
class MainClass
{
    public static void Main()
    {
        Counter MyCounter = new Counter();
        EvenNumberHandlerClass MyEvenNumberHandlerClass = new EvenNumberHandlerClass();
        MyCounter.OnEvenNumber += new EvenNumberHandler(MyEvenNumberHandlerClass.EvenNumberFound);
        MyCounter.CountTo100();
    }
}

Retrieving Even-Numbered Events with the .NET Delegate Convention

using System;
   
public delegate void EvenNumberHandler(object Originator, OnEvenNumberEventArgs EvenNumberEventArgs);
   
class Counter
{
    public event EvenNumberHandler OnEvenNumber;
   
    public Counter()
    {
        OnEvenNumber = null;
    }
   
    public void CountTo100()
    {
        int CurrentNumber;
   
        for(CurrentNumber = 0; CurrentNumber <= 100; CurrentNumber++)
        {
            if(CurrentNumber % 2 == 0)
            {
                if(OnEvenNumber != null)
                {
                    OnEvenNumberEventArgs EventArguments;
   
                    EventArguments = new OnEvenNumberEventArgs(CurrentNumber);
                    OnEvenNumber(this, EventArguments);
                }
            }
        }
    }
}
   
public class OnEvenNumberEventArgs : EventArgs
{
    private int EvenNumber;
   
    public OnEvenNumberEventArgs(int EvenNumber)
    {
        this.EvenNumber = EvenNumber;
    }
   
    public int Number
    {
        get
        {
            return EvenNumber;
        }
    }
}
   
class EvenNumberHandlerClass
{
    public void EvenNumberFound(object Originator, OnEvenNumberEventArgs EvenNumberEventArgs)
    {
        Console.WriteLine(EvenNumberEventArgs.Number);
    }
}
   
class MainClass
{
    public static void Main()
    {
        Counter MyCounter = new Counter();
        EvenNumberHandlerClass MyEvenNumberHandlerClass = new EvenNumberHandlerClass();
        MyCounter.OnEvenNumber += new EvenNumberHandler(MyEvenNumberHandlerClass.EvenNumberFound);
        MyCounter.CountTo100();
    }
}

Using The Event Keyword

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
    public class MyEventArgs : EventArgs
    {
        public readonly int Hour;
        public readonly int Minute;
        public readonly int Second;
        public MyEventArgs(int hour, int minute, int second)
        {
            this.Hour = hour;
            this.Minute = minute;
            this.Second = second;
        }
    }
    public delegate void MyHandler(object clock,MyEventArgs timeInformation);
    public class Clock
    {
        private int hour;
        private int minute;
        private int second;
        public event MyHandler SecondChanged;
        protected virtual void OnSecondChanged(MyEventArgs e)
        {
            if (SecondChanged != null)
            {
                SecondChanged(this, e);
            }
        }
        public void Run()
        {
            for (; ; )
            {
                System.DateTime dt = System.DateTime.Now;
                if (dt.Second != second){
                    MyEventArgs timeInformation =new MyEventArgs(dt.Hour, dt.Minute, dt.Second);
                    OnSecondChanged(timeInformation);
                }
                this.second = dt.Second;
                this.minute = dt.Minute;
                this.hour = dt.Hour;
            }
        }
    }
    public class ConsoleHandler
    {
        public void Register(Clock theClock)
        {
            theClock.SecondChanged += new MyHandler(TimeHasChanged);
        }
        public void TimeHasChanged(object theClock, MyEventArgs ti)
        {
            Console.WriteLine("Current Time: {0}:{1}:{2}",ti.Hour.ToString(),ti.Minute.ToString(),ti.Second.ToString());
        }
    }
    public class Test
    {
        public static void Main()
        {
            Clock theClock = new Clock();
            ConsoleHandler dc = new ConsoleHandler();
            dc.Register(theClock);
            theClock.Run();
        }
    }