From this brief description, it can be seen that delegates are functionally rather similar to C++'s 'function pointers'. However, it is important to bear in mind two main differences. Firstly, delegates are reference types rather than value types. Secondly, some single delegates can reference multiple methods
Delegate
Declaration and Instantiation
Delegates
can be specified on their own in a namespace, or else can be specified within
another class (the examples below all show the latter). In each case, the
declaration specifies a new class, which inherits from
System.MulticastDelegate. Each delegate is limited to referencing methods of a particular kind only. The type is indicated by the delegate declaration - the input parameters and return type given in the delegate declaration must be shared by the methods its delegate instances reference. To illustrate this: a delegate specified as below can be used to refer only to methods which have a single String input and no return value:
public delegate void
Print (String s);
Suppose,
for instance, that a class contains the following method:
|
Print delegateVariable
= new Print(realMethod);
We can
note two important points about this example. Firstly, the unqualified method
passed to the delegate constructor is implicitly recognised as a method of the
instance passing it. That is, the code is equivalent to:
Print delegateVariable
= new Print(this.realMethod);
We can,
however, in the same way pass to the delegate constructor the methods of other
class instances, or even static class methods. In the case of the former, the
instance must exist at the time the method reference is passed. In the case of
the latter (exemplified below), the class need never be instantiated.
Print delegateVariable
= new Print(ExampleClass.exampleMethod);
The
second thing to note about the example is that all delegates can be constructed
in this fashion, to create a delegate instance which refers to a single method.
However, as we noted before, some delegates - termed 'multicast delegates' -
can simultaneously reference multiple methods. These delegates must - like our
Print delegate - specify a 'void' return type. One manipulates the references of multicast delegates by using addition and subtraction operators (although delegates are in fact immutable reference types ) The following code gives some examples:
|
The following code gives an example of the use of delegates. In the Main method, the Print delegate is instantiated twice, taking different methods. These Print delegates are then passed to the Display method, which by invoking the Print delegate causes the method it holds to run. As an exercise, you could try rewriting the code to make Print a multicast delegate.
|
No comments:
Post a Comment