How to: Declare, Instantiate, and Use a Delegate
In C# 1.0 and later, delegates can be declared as shown in the following example.
// Declare a delegate. delegate void Del(string str); // Declare a method with the same signature as the delegate. static void Notify(string name) { Console.WriteLine("Notification received for: {0}", name); }
// Create an instance of the delegate. Del del1 = new Del(Notify);
C# 2.0 provides a simpler way to write the previous declaration, as shown in the following example.
// C# 2.0 provides a simpler way to declare an instance of Del.
Del del2 = Notify;
In C# 2.0 and later, it is also possible to use an anonymous method to declare and initialize a delegate, as shown in the following example.
// Instantiate Del by using an anonymous method. Del del3 = delegate(string name) { Console.WriteLine("Notification received for: {0}", name); };
In C# 3.0 and later, delegates can also be declared and instantiated by using a lambda expression, as shown in the following example.
// Instantiate Del by using a lambda expression. Del del4 = name => { Console.WriteLine("Notification received for: {0}", name); };
For more information, see Lambda Expressions (C# Programming Guide).
The following example illustrates declaring, instantiating, and using a delegate. The BookDB class encapsulates a bookstore database that maintains a database of books. It exposes a method, ProcessPaperbackBooks, which finds all paperback books in the database and calls a delegate for each one. The delegate type that is used is named ProcessBookDelegate. The Test class uses this class to print the titles and average price of the paperback books.
The use of delegates promotes good separation of functionality between the bookstore database and the client code. The client code has no knowledge of how the books are stored or how the bookstore code finds paperback books. The bookstore code has no knowledge of what processing is performed on the paperback books after it finds them.
첫번째 방법은 까마득히 잊고 있었다.
댓글
댓글 쓰기