C # 2.0 Learning - Event 1

xiaoxiao2021-04-08  433

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

// Events1.csusing system; namespace mycollection {using system.collections;

// a delegate Type for hooking up changeding up change DELEGATE VOID CHANGEDEVENTHANDLER (Object Sender, Eventargs E);

// 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 ChangedendHandler Changed;

// invoke the change Event; Called WHENEVER LIST CHANGES PROTECTED VIRTAL VOID ONCHANGED (EVENTARGS E) {IF (Changed! = Null) Changed (this, e);}

// Override Some of The Methods That Can Change The List; // INVOKE EVENT AFTER EACH PUBLIC OVERRIDE INT Add (Object Value) {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; // add "listchanged" to the change Event on "list". list.changed = new changeeventhandler (listchanged);

// this Will Be Called WHENEVER THE LIST CHANGES. Private Void ListChanged ("this is caled when evenet fires.");} Public void detach () {// Detach the Event And delete the list list.changed - = new changedEventhandler (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"); list.com} ();}}}

CSC Events1.cs

Events1

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

New Post(0)