X hits on this document





307 / 396

Chapter ‎18   Unsafe code

15. Delegates

Delegates enable scenarios that other languages—such as C++, Pascal, and Modula—have addressed with function pointers. Unlike C++ function pointers, however, delegates are fully object oriented, and unlike C++ pointers to member functions, delegates encapsulate both an object instance and a method.

A delegate declaration defines a class that is derived from the class System.Delegate. A delegate instance encapsulates an invocation list, which is a list of one or more methods, each of which is referred to as a callable entity. For instance methods, a callable entity consists of an instance and a method on that instance. For static methods, a callable entity consists of just a method. Invoking a delegate instance with an appropriate set of arguments causes each of the delegate’s callable entities to be invoked with the given set of arguments.

An interesting and useful property of a delegate instance is that it does not know or care about the classes of the methods it encapsulates; all that matters is that those methods be compatible (§‎15.1) with the delegate’s type. This makes delegates perfectly suited for “anonymous” invocation.

15.1 Delegate declarations

A delegate-declaration is a type-declaration (§‎9.5) that declares a new delegate type.

delegate-declaration: attributesopt   delegate-modifiersopt   delegate   return-type   identifier (   formal-parameter-listopt   )   ;

delegate-modifiers: delegate-modifier delegate-modifiers   delegate-modifier

delegate-modifier: new public protected internal private

It is a compile-time error for the same modifier to appear multiple times in a delegate declaration.

The new modifier is only permitted on delegates declared within another type, in which case it specifies that such a delegate hides an inherited member by the same name, as described in §‎10.2.2.

The public, protected, internal, and private modifiers control the accessibility of the delegate type. Depending on the context in which the delegate declaration occurs, some of these modifiers may not be permitted (§‎3.5.1).

The delegate’s type name is identifier.

The optional formal-parameter-list specifies the parameters of the delegate, and return-type indicates the return type of the delegate. A method and a delegate type are compatible if both of the following are true:

They have the same number or parameters, with the same types, in the same order, with the same parameter modifiers.

Their return types are the same.

Copyright Microsoft Corporation 1999-2003. All Rights Reserved.294

Document info
Document views1284
Page views1284
Page last viewedFri Jan 20 20:55:35 UTC 2017