Sie sind auf Seite 1von 12

Delegate

You can call the delegate by giving the name of the


delegate and by passing parameters, if required.
Using delegates is similar to calling methods.

Delegate (Contd.)

The following example shows how to use a delegate:


using System;
using System.IO;
// Program to write the data to the console and
file
namespace Chapter12_Ex1
{
public class PrintToDevice
{
//Creating the variables of Stream classes
static FileStream FStream;
static StreamWriter SWriter;
//Defining a Delegate
//Method to send the string data to respective
methods

Using Delegate (Contd.)


//removing the content from the buffer
SWriter.Flush();
SWriter.Close();
FStream.Close();
}
public delegate void PrintData(String s);
//Method to print a string to the console
public static void WriteConsole (string str)
{
Console.WriteLine("{0} Console", str);
}
//Method to print a string to a file
public static void WriteFile (string s)

Using Delegate (Contd.)


{
//Initializing stream objects
FStream = new FileStream("c:\\StoreData.txt",
FileMode.Append, FileAccess.Write);
SWriter = new StreamWriter(FStream);
s= s + " File";
//Writing a string to the file
SWriter.WriteLine(s);
}
public static void DisplayData(PrintData PMethod)
{
PMethod ("This should go to the");
}
public static void Main()

Using Delegate
{
//Initializing the Delegate object
PrintData Cn = new PrintData (WriteConsole);
PrintData Fl = new PrintData (WriteFile);
//Invoking the DisplayData method with the
Delegate object as the argument
//Using Delegate
DisplayData (Cn);
DisplayData (Fl);
Console.ReadLine();
}
}
}

Types of Delegates
Delegates are of two types and depending upon the
requirement of the application the suitable type of delegate
is selected.

Types of Delegates (Contd.)


There are two types of delegates:
Single-cast delegate
Multicast delegate

Single-Cast Delegate
A single-cast delegate derives from the System.Delegate
class.
It contains reference to one method only at a time.

Multicast Delegate
A multicast delegate derives from the
System.MulticastDelegate class.
It contains an invocation list of multiple methods. In
multicasting you create a single delegate that invokes
multiple encapsulated methods.
Multicast delegates hold the reference of more than one
method therefore, if you call a multicast delegate it will
executes all the methods it wraps in the calling order.
The multiple methods called by the delegate in this case
should not return any value. Several multicast delegates are
called consecutively and you cannot wait to get the return
value from each of these methods.

Just a minute
State whether the following statement is True or False.
Multicast delegates inherit from the
System.Delegate.MulticastDelegate class.

Answer:
False

Working with Events


An event is an action or occurrence, such as clicks, key
presses, mouse movements, or system generated
notifications.
Applications can respond to events when they occur.

Das könnte Ihnen auch gefallen