C # 2.0 Learning - Event 2

xiaoxiao2021-04-08  4

// Copyright (c) Microsoft Corporation. All Rights Reserved.

// Events2.csusing system; namespace mycollection;

// A class that works just like ArrayList, but sends event // notifications whenever the list changes: public class ListWithChangedEvent: ArrayList {// An event that clients can use to be notified whenever the // elements of the list change: public event EventHandler Changed;

// Invoke the change Event; Called WHENEVER LIST CHANGES: Protected Virtual Void Onchanged (Eventargs E) {if (Changed! = Null) Changed (this, e);}

// Override some of the method; // invoke event after each: public override int address {int i = base.add (value); onchanged (evenTargs.empty); Return i;}

Public override void clear () {base.clear (); onchanged (eventargs.empty);

Public override object this [int index] {set {base [index] = value; onchanged (eventargs.empty);}}}}

Namespace TESTEVENTS {Using MyCollections

Class EventListener {Private ListwithchangeDevent List;

Public eventlistener (list = list; // address "listchanged" to the change Event on "list": list.changed = new eventhandler (listchanged);

// this Will Be Called WHENEVER THE LIST CHANGES: Private Void ListChanged (Object Sender, Eventargs E) {Console.Writeline ("this is caled when evenet Fires);}

public void Detach () {// Detach the event and delete the list: List.Changed - = new EventHandler (ListChanged); List = null;}} class Test {// Test the ListWithChangedEvent class: public static void Main () { // Create a new list: listwithchangedevent list = new listwithchangedevent ();

// Create a class thing listens to the list's change Event: EventListener Listener = New EventListener (List);

// Add and remove items from the list: list .add ("item 1"); listner.detach ();}}}

CSC Events2.cs


转载请注明原文地址: http://www.9cbs.com/read-132890.html

New Post(0)