C # DEMO code of delegation Mechanism

Source: Internet
Author: User


Figure 1 delegation demonstration with EventArgs

Figure 2 Delegate demonstration without EventArgs

Download the source code in this example:
1. Delegate without Parameters
2. Delegate with Parameters

The source code of the delegate demo with EventArgs is as follows:

Using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Data;
Using System. Drawing;
Using System. Linq;
Using System. Text;
Using System. Windows. Forms;
Using System. Collections;
Using System. Diagnostics;

Namespace WindowsFormsApplication8
{
Public partial class Form1: Form
{
Public static TextBox ttt = null;
Public Form1 ()
{
Initializecomponent ();
TTT = This. textbox1;

}

P rivate void button#click (Object sender, eventargs E)
{
Employee employee1 = new employee ();
Employee1.age = 33;
Employee1.name = "";
Admin admin1 = new admin ();
Employee1.playgame + = new delegate1 (admin1.notify );
Employee1.games ();

}

P rivate class employee
{
String name = "";
Int age = 0;
Public event delegate1 playgame;

Public String Name
{
Get {return this. name ;}
Set {this. name = value ;}
}

Public int Age
{
Get {return this. age ;}
Set {this. age = value ;}
}

Public void games ()
{
If (playgame! = Null)
{
Custom e = new custom ();
E. Age = this. age;
E. Name = This. Name;
Playgame (this, e );
}
}
}

P rivate class Admin
{

Public void notify (Object sender, custom E)
{
Form1.ttt. Text = e. Name + playing the game! Age: "+ e. Age. ToString () +" hour ?;
}
}

Public delegate void delegate1 (object sender, custom e );

Public class custom: EventArgs
{
String name = "";
Int age = 0;

Public String Name
{
Set {this. name = value ;}
Get {return this. name ;}
}

Public int Age
{
Set {this. age = value ;}
Get {return this. age ;}
}
}

}
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.