Delegate (Event) Sample

xiaoxiao2021-03-06  86

Using system;

Namespace Csharpconsole

{

Public class scene

{

[Stathread]

Public static void main (string [] args)

{

Console.writeline ("Scene starts ...");

/ / Generate Xiao Wang

Xiao Wang W = New Xiao Wang ();

// Generate a small account

Small Zhang Z = New Small ();

/ / Specify monitoring

z.PlayGame = New PlayGameHandler (w. Deduction);

// Start playing games

Z. Play games ();

Console.writeline ("Scene end ...");

Console.readline ();

}

}

/ / People responsible for deducting money

Public Class Xiao Wang

{

Public king ()

{

Console.writeline ("Generate Xiao Wang ...");

}

Public void deduction (Object Sender, Eventargs E)

{

Console.Writeline ("Xiao Wang: Good kid, go to work dare to play games ...");

Console.writeline ("Xiao Wang: See how much your kid is ...");

Small Zhang f = (small sheet) Sender;

Console.writeLine ("Small Money:" f. Money .toString ());

Console.writeline ("Start to deliver money ...");

System.threading.Thread.sleep (500);

f. Money = f. Money - 500;

Console.writeline ("After the deduction .... Now Xiao Zhang still remains:" f. Money .toString ());

}

}

// If you play games, an event is triggered

Public Class small

{

// First define an event, this event means "small" in playing games.

Public Event PlayGameHandler PlayGame;

/ / Save a variable of small money

PRIVATE INT M_MONEY;

Public small ()

{

Console.writeline ("Generate Small ....");

m_money = 1000; // Constructor, initialize the money of small

}

Public int money // This property can operate small money.

{

get

{

RETURN M_MONEY;

}

set

{

M_Money = Value;

}

}

Public void playing games ()

{

Console.writeline ("Xiao Zhang starts to play games .....");

Console.writeline ("Small Zhang: CS fun, hahaha! I play .....");

System.threading.Thread.sleep (500);

System.eventargs e = new evenetargs ();

OnPlayGame (e);

}

Protected Virtual Void OnPlayGame (Eventargs E)

{

IF (PlayGame! = NULL)

{

PlayGame (this, e);

}

}

}

// Define the delegation handler

Public Delegate Void PlayGameHandler (Object Sender, System.EventArgs E);

}

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

New Post(0)