Guide to the Language
Download 2 Mb. Pdf ko'rish
|
C sharp
- Bu sahifa navigatsiya:
- Delegates as Parameters
Delegate Signature
As mentioned, a method can be assigned to a delegate object if it matches the delegate’s signature. However, a method does not have to match the signature exactly. A delegate object can also refer to a method that has a more derived return type than that defined in the delegate, or that has parameter types that are ancestors of the corresponding delegate’s parameter types. class Base {} class Derived : Base {} delegate Base MyDelegate(Derived d); class MyClass { static Derived Test(Base o) { return new Derived(); } Chapter 26 Delegates 151 static void Main() { MyDelegate d = Test; } } Delegates as Parameters An important property of delegates is that they can be passed as method parameters. To demonstrate the benefit of this, two simple classes will be defined. The first one is a data storage class called PersonDB that has an array containing a couple of names. It also has a method that takes a delegate object as its argument and calls that delegate for each name in the array. delegate void ProcessPersonDelegate(string name); class PersonDB { string[] list = { "John", "Sam", "Dave" }; public void Process(ProcessPersonDelegate f) { foreach(string s in list) f(s); } } The second class is Client, which will use the storage class. It has a Main method that creates an instance of PersonDB, and it calls that object’s Process method with a method that is defined in the Client class. Chapter 26 Delegates 152 class Client { static void Main() { PersonDB p = new PersonDB(); p.Process(PrintName); } static void PrintName(string name) { System.Console.WriteLine(name); } } The benefit of this approach is that it allows the implementation of the data storage to be separated from the implementation of the data processing. The storage class only handles the storage and has no knowledge of the processing that is done on the data. This allows the storage class to be written in a more general way than if this class had to implement all of the potential processing operations that a client may want to perform on the data. With this solution, the client can simply plug its own processing code into the existing storage class. Chapter 26 Delegates 153 © Mikael Olsson 2020 M. Olsson, C# 8 Quick Syntax Reference, https://doi.org/10.1007/978-1-4842-5577-3_27 Download 2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling