. Thus, they match the
delegate. These
methods perform some type of string modification. Notice that
ReplaceSpaces( )
, to replace spaces with hyphens.
. Pay close attention to this line:
is passed as a parameter. Only its name is used;
no parameters are specified. This can be generalized. When instantiating a delegate, you
specify only the name of the method to which you want the delegate to refer. Of course, the
method’s signature must match that of the delegate’s declaration. If it doesn’t, a compile-
time error will result.
402
P a r t I :
T h e C # L a n g u a g e
Next,
strOp
is assigned a reference to
RemoveSpaces( )
, and then
strOp
is called again.
This time,
RemoveSpaces( )
is invoked.
Finally,
strOp
is assigned a reference to
Reverse( )
and
strOp
is called. This results in
Reverse( )
being called.
The key point of the example is that the invocation of
strOp
results in a call to the method
referred to by
strOp
at the time at which the invocation occurs. Thus, the method to call is
resolved at runtime, not compile time.
Delegate Method Group Conversion
Beginning with version 2.0, C# has included an option that significantly simplifies the
syntax that assigns a method to a delegate. This feature is called
method group conversion,
and it allows you to simply assign the name of a method to a delegate, without using
new
or explicitly invoking the delegate’s constructor.
For example, here is the
Main( )
method of the preceding program rewritten to use
method group conversions:
static void Main() {
// Construct a delegate using method group conversion.
StrMod strOp = ReplaceSpaces; // use method group conversion
string str;
// Call methods through the delegate.
str = strOp("This is a test.");
Console.WriteLine("Resulting string: " + str);
Console.WriteLine();
strOp = RemoveSpaces; // use method group conversion
str = strOp("This is a test.");
Console.WriteLine("Resulting string: " + str);
Console.WriteLine();
strOp = Reverse; // use method group conversion
str = strOp("This is a test.");
Console.WriteLine("Resulting string: " + str);
}
Pay special attention to the way that
strOp
is created and assigned the method
ReplaceSpaces
in this line:
StrMod strOp = ReplaceSpaces; // use method group conversion
The name of the method is assigned directly to
strOp
. C# automatically provides a
conversion from the method to the delegate type. This syntax can be generalized to any
situation in which a method is assigned to (or converted to) a delegate type.
Because the method group conversion syntax is simpler than the old approach, it is used
throughout the remainder of this book.
Using Instance Methods as Delegates
Although the preceding example used
static
methods, a delegate can also refer to instance
methods. It must do so, however, through an object reference. For example, here is a rewrite
of the previous example, which encapsulates the string operations inside a class called
www.freepdf-books.com