共用方式為


Delegates (C# Programming Guide) 

A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value, as in this example:

public delegate int PerformCalculation(int x, int y);

Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate. This makes is possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the delegate's signature, you can assign your own delegated method.

This ability to refer to a method as a parameter makes delegates ideal for defining callback methods. For example, a sort algorithm could be passed a reference to the method that compares two objects. Separating the comparison code allows the algorithm to be written in a more general way.

Delegates Overview

Delegates have the following properties:

  • Delegates are similar to C++ function pointers, but are type safe.

  • Delegates allow methods to be passed as parameters.

  • Delegates can be used to define callback methods.

  • Delegates can be chained together; for example, multiple methods can be called on a single event.

  • Methods don't need to match the delegate signature exactly. For more information, see Covariance and Contravariance

  • C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately defined method.

In This Section

C# Language Specification

For more information, see the following sections in the C# Language Specification:

  • 1.11 Delegates

  • 4.2.6 Delegate types

  • 7.5.5.2 Delegate invocations

  • 15 Delegates

See Also

Reference

Delegate

Concepts

C# Programming Guide
Events (C# Programming Guide)