Delegates
attributes
?
access-modifier
?
|
new?
|
delegate
|
[
void | type
]
|
delegate
-
name
(
parameter-list
);
|
A delegate is a type that defines a method signature, so that delegate instances can hold and invoke a method or list of methods that match its signature. A delegate declaration consists of a name and a method signature.[1]
Here’s an example:
delegate bool Filter(string s);
This declaration lets you create delegate instances that can hold and
invoke methods that return bool
and have a single
string parameter. In the following example a
Filter
is created that holds the
FirstHalf-OfAlphabet
method. You then pass the
Filter
to the Display
method,
which invokes the Filter
:
class Test { static void Main( ) { Filter f = new Filter(FirstHalfOfAlphabet); Display(new String [] {"Ant","Lion","Yak"}, f); } static bool FirstHalfOfAlphabet(string s) { return "N".CompareTo(s) > 0; } static void Display(string[] names, Filter f) { int count = 0; foreach(string s in names) if(f(s)) // invoke delegate Console.WriteLine("Item {0} is {1}", count++, s); } }
Multicast Delegates
If a
delegate
has a void return type, it is a multicast
delegate that can hold and invoke multiple methods. In this example,
we declare a simple delegate called MethodInvoker
,
which can hold and then invoke the Foo
and
Goo
methods sequentially. The
+=
method creates a new delegate by adding the
right delegate operand to the left delegate operand.
delegate void MethodInvoker( ); class Test { static void Main( ) { new Test( ...
Get C# Essentials now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.