- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
Delegates
This part of the C# tutorial is dedicated to delegates.
A delegate is a form of type-safe function pointer used by the .NET Framework. Delegates are often used to implement callbacks and event listeners. A delegate does not need to know anything about classes of methods it works with.
A delegate is a reference type. But instead of referring to an object, a delegate refers to a method.
Delegates are used in the following cases:
- Event handlers
- Callbacks
- LINQ
- Implementation of design patterns
There is nothing that is done with delegates that cannot be done with regular methods. Delegates are used because they bring several advantages. They foster flexibility of the application and code reuse. Like interfaces, delegates let us decouple and generalize our code. Delegates also allow methods to be passed as parameters. When we need to decide which method to call at runtime, we use a delegate. Finally, delegates provide a way of specializing behavior of a class without subclassing it. Classes may have complex generic behavior but are still meant to be specialized. Classes are specialized either through inheritance or via delegates.
Using delegates
We will have some simple examples showing how to use delegates.
using System; delegate void Mdelegate(); public class SimpleDelegate { static void Main() { Mdelegate del = new Mdelegate(Callback); del(); } static void Callback() { Console.WriteLine("Calling callback"); } }
We declare a delegate, create an instance of the delegate and invoke it.
delegate void Mdelegate();
This is our delegate declaration. It returns no value and takes no parameters.
Mdelegate del = new Mdelegate(Callback);
We create an instance of the delegate. When called, the delegate will invoke the static Callback()
method.
del();
We call the delegate.
$ ./simple.exe Calling callback
This is the output.
We can use a different syntax for creating and using a delegate.
using System; delegate void Mdelegate(); public class SimpleDelegate2 { static void Main() { Mdelegate del = Callback; del(); } static void Callback() { Console.WriteLine("Calling callback"); } }
We can save some typing when creating an instance of a delegate. This was introduced in C# 2.0.
Mdelegate del = Callback;
This is another way of creating a delegate. We point directly to the method name.
A delegate can point to different methods over time.
using System; public delegate void NameDelegate(string msg); public class Person { public string firstName; public string secondName; public Person(string firstName, string secondName) { this.firstName = firstName; this.secondName = secondName; } public void ShowFirstName(string msg) { Console.WriteLine(msg + this.firstName); } public void ShowSecondName(string msg) { Console.WriteLine(msg + this.secondName); } } public class CSharpApp { public static void Main() { Person per = new Person("Fabius", "Maximus"); NameDelegate nDelegate = new NameDelegate(per.ShowFirstName); nDelegate("Call 1: "); nDelegate = new NameDelegate(per.ShowSecondName); nDelegate("Call 2: "); } }
In the example we have one delegate. This delegate is used to point to two methods of the Person class. The methods are called with the delegate.
public delegate void NameDelegate(string msg);
The delegate is created with a delegate
keyword. The delegate signature must match the signature of the method being called with the delegate.
NameDelegate nDelegate = new NameDelegate(per.ShowFirstName); nDelegate("Call 1: ");
We create an instance of a new delegate that points to the ShowFirstName()
method. Later we call the method via the delegate.
$ ./moremethods.exe Call 1: Fabius Call 2: Maximus
Both names are printed via the delegate.
Multicast delegate
Multicast delegate is a delegate which holds a reference to more than one method. Multicast delegates must contain only methods that return void, else there is a run-time exception.
using System; delegate void Mdelegate(int x, int y); public class Oper { public static void Add(int x, int y) { Console.WriteLine("{0} + {1} = {2}", x, y, x + y); } public static void Sub(int x, int y) { Console.WriteLine("{0} - {1} = {2}", x, y, x - y); } } public class CSharpApp { static void Main() { Mdelegate del = new Mdelegate(Oper.Add); del += new Mdelegate(Oper.Sub); del(6, 4); del -= new Mdelegate(Oper.Sub); del(2, 8); } }
This is an example of a multicast delegate.
delegate void Mdelegate(int x, int y);
Our delegate will take two parameters. We have an Oper class which has two static methods. One adds two values the other one subtracts two values.
Mdelegate del = new Mdelegate(Oper.Add);
We create an instance of our delegate. The delegate points to the static Add()
method of the Oper
class.
del += new Mdelegate(Oper.Sub); del(6, 4);
We plug another method to the existing delegate instance. The first call of the delegate invokes two methods.
del -= new Mdelegate(Oper.Sub); del(2, 8);
We remove one method from the delegate. The second call of the delegate invokes only one method.
$ ./multicast.exe 6 + 4 = 10 6 - 4 = 2 2 + 8 = 10
This is the output of the multicast.exe
program.
Anonymous methods
It is possible to use anonymous methods with delegates.
using System; delegate void Mdelegate(); public class Anonymous { static void Main() { Mdelegate del = delegate { Console.WriteLine("Anonymous method"); }; del(); } }
We can omit a method declaration when using an anonymous method with a delegate. The method has no name and can be invoked only via the delegate.
Mdelegate del = delegate { Console.WriteLine("Anonymous method"); };
Here we create a delegate that points to an anonymous method. The anonymous method has a body enclosed by { } characters, but it has no name.
Delegates as method parameters
Delegates can be used as method parameters.
using System; delegate int Arithm(int x, int y); public class CSharpApp { static void Main() { DoOperation(10, 2, Multiply); DoOperation(10, 2, Divide); } static void DoOperation(int x, int y, Arithm del) { int z = del(x, y); Console.WriteLine(z); } static int Multiply(int x, int y) { return x * y; } static int Divide(int x, int y) { return x / y; } }
We have a DoOperation()
method which takes a delegate as a parameter.
delegate int Arithm(int x, int y);
This is a delegate declaration.
static void DoOperation(int x, int y, Arithm del) { int z = del(x, y); Console.WriteLine(z); }
This is DoOperation()
method implementation. The third parameter is a delegate. The DoOperation()
method calls a method which is passed to it as a third parameter.
DoOperation(10, 2, Multiply); DoOperation(10, 2, Divide);
We call the DoOperation()
method. We pass two values and a method to it. What we do with the two values depends on the method that we pass. This is the flexibility that come with using delegates.
Events
Events are messages triggered by some action. A click on a button or a tick of a clock are such actions. The object that triggers an event is called a sender and the object that receives the event is called a receiver.
By convention, event delegates in the .NET Framework have two parameters: the source that raised the event and the data for the event.
using System; public delegate void OnFiveHandler(object sender, EventArgs e); class FEvent { public event OnFiveHandler FiveEvent; public void OnFiveEvent() { if(FiveEvent != null) FiveEvent(this, EventArgs.Empty); } } public class SimpleEvent { static void Main() { FEvent fe = new FEvent(); fe.FiveEvent += new OnFiveHandler(Callback); Random random = new Random(); for (int i = 0; i<10; i++) { int rn = random.Next(6); Console.WriteLine(rn); if (rn == 5) { fe.OnFiveEvent(); } } } public static void Callback(object sender, EventArgs e) { Console.WriteLine("Five Event occured"); } }
We have a simple example in which we create and launch an event. An random number is generated. If the number equals to 5 a FiveEvent
event is generated.
public event OnFiveHandler FiveEvent;
An event is declared with a event
keyword.
fe.FiveEvent += new OnFiveHandler(Callback);
Here we plug the event called FiveEvent
to the Callback()
method. In other words, if the ValueFive
event is triggered, the Callback()
method is executed.
public void OnFiveEvent() { if(FiveEvent != null) FiveEvent(this, EventArgs.Empty); }
When the random number equals to 5, we invoke the OnFiveEvent()
method. In this method, we raise the FiveEvent
event. This event carries no arguments.
$ ./simpleevent.exe 3 0 5 Five Event occured 0 5 Five Event occured 2 3 4 4 0
The output of the program might look like this.
Complex event example
Next we have a more complex example. This time we will send some data with the generated event.
using System; public delegate void OnFiveHandler(object sender, FiveEventArgs e); public class FiveEventArgs : EventArgs { public int count; public DateTime time; public FiveEventArgs(int count, DateTime time) { this.count = count; this.time = time; } } public class FEvent { public event OnFiveHandler FiveEvent; public void OnFiveEvent(FiveEventArgs e) { FiveEvent(this, e); } } public class RandomEventGenerator { public void Generate() { int count = 0; FiveEventArgs args; FEvent fe = new FEvent(); fe.FiveEvent += new OnFiveHandler(Callback); Random random = new Random(); for (int i = 0; i<10; i++) { int rn = random.Next(6); Console.WriteLine(rn); if (rn == 5) { count++; args = new FiveEventArgs(count, DateTime.Now); fe.OnFiveEvent(args); } } } public void Callback(object sender, FiveEventArgs e) { Console.WriteLine("Five event {0} occured at {1}", e.count, e.time); } } public class ComplexEvent { static void Main() { RandomEventGenerator reg = new RandomEventGenerator(); reg.Generate(); } }
We have four classes. The FiveEventArgs
carries some data with the event object. The FEvent
class encapsulates the event object. The RandomEventGenerator
class is responsible for random number generation. It is the event sender. Finally, the ComplexEvent
is the main application class.
public class FiveEventArgs : EventArgs { public int count; public DateTime time; ...
The FiveEventArgs
carries data inside the event object. It inherits from the EventArgs
base class. The count and time members are data that will be initialized and carried with the event.
if (rn == 5) { count++; args = new FiveEventArgs(count, DateTime.Now); fe.OnFiveEvent(args); }
If the generated random number equals to 5, we instantiate the FiveEventArgs
class with the current count and DateTime
values. The count
variable counts the number of times this event was generated. The DateTime
value holds the time when the event was generated.
$ ./complexevent.exe 2 2 3 5 Five event 1 occured at 11/7/2010 12:13:59 AM 5 Five event 2 occured at 11/7/2010 12:13:59 AM 1 1 0 5 Five event 3 occured at 11/7/2010 12:13:59 AM 5 Five event 4 occured at 11/7/2010 12:13:59 AM
This is a sample output of the complexevent.exe program.
Predefined delegates
The .NET framework has several built-in delegates that a reduce the typing needed and make the programming easier for developers.
An action delegate encapsulates a method that has no parameters and does not return a value.
using System; public class ActionDelegate { static void Main() { Action act = ShowMessage; act(); } static void ShowMessage() { Console.WriteLine("C# language"); } }
Using predefined delegates further simplifies programming. We do not need to declare a delegate type.
Action act = ShowMessage; act();
We instantiate an action delegate. The delegate points to the ShowMessage()
method. When the delegate is invoked, the ShowMessage()
method is executed.
There are multiple types of action delegates. For example, the Action<T>
delegate encapsulates a method that takes a single parameter and does not return a value.
using System; public class CSharpApp { static void Main() { Action<string> act = ShowMessage; act("C# language"); } static void ShowMessage(string message) { Console.WriteLine(message); } }
We modify the previous example to use the action delegate that takes one parameter.
Action<string> act = ShowMessage; act("C# language");
We create an instance of the Action<T> delegate and call it with one parameter.
Predicate delegate
A predicate is a method that returns true or false. A predicate delegate is a reference to a predicate. Predicates are very useful for filtering lists of values.
using System; using System.Collections.Generic; public class PredicateDelegate { static void Main() { List<int> list = new List<int> { 4, 2, 3, 0, 6, 7, 1, 9 }; Predicate<int> predicate = greaterThanThree; List<int> list2 = list.FindAll(predicate); foreach ( int i in list2) { Console.WriteLine(i); } } static bool greaterThanThree(int x) { return x > 3; } }
We have a list of integer values. We want to filter all numbers that are bigger than three. For this, we use the predicate delegate.
List<int> list = new List<int> { 4, 2, 3, 0, 6, 7, 1, 9 };
This is a generic list of integer values.
Predicate<int> predicate = greaterThanThree;
We create an instance of a predicate delegate. The delegate points to a predicate, a special method that returns true or false.
List<int> list2 = list.FindAll(predicate);
The FindAll()
method retrieves all the elements that match the conditions defined by the specified predicate.
static bool greaterThanThree(int x) { return x > 3; }
The predicate returns true for all values that are greater than three.
This part of the C# tutorial was dedicated to the delegates.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论