delegate 可以與具名方法產生關聯。 當您使用具名方法具現化委派時,方法會當做參數傳遞,例如:
// Declare a delegate.
delegate void WorkCallback(int x);
// Define a named method.
void DoWork(int k) { /* ... */ }
// Instantiate the delegate using the method as a parameter.
WorkCallback d = obj.DoWork;
上述範例使用具名方法。 使用具名方法建構的委派可封裝靜態方法或執行個體方法。 在舊版 C# 中,要具現化委派只能使用具名方法。 C# 可讓您具現化委派,並立即指定委派在呼叫時處理的程式代碼區塊。 區塊可以包含 Lambda 表達式 或 匿名方法,如下列範例所示:
// Declare a delegate.
delegate void WorkCallback(int x);
// Instantiate the delegate using an anonymous method.
WorkCallback d = (int k) => { /* ... */ };
當做委派參數傳遞的方法必須擁有與委派宣告相同的簽章。 委派實例可以封裝靜態或實例方法。
注意
即使委派可使用 out 參數,但仍不建議您用於多點傳送事件委派,因為無從得知將呼叫哪一個委派。
具有單一多載的方法群組具有 自然類型。 編譯程式可以推斷委派類型的傳回類型和參數類型:
var read = Console.Read; // Just one overload; Func<int> inferred
var write = Console.Write; // ERROR: Multiple overloads, can't choose
範例
以下例子是宣告和使用委派的簡單示例。 請注意,委派 MultiplyCallback 和相關聯的方法 MultiplyNumbers 必須擁有相同的簽章
// Declare a delegate
delegate void MultiplyCallback(int i, double j);
class MathClass
{
static void Main()
{
MathClass m = new MathClass();
// Delegate instantiation using "MultiplyNumbers"
MultiplyCallback d = m.MultiplyNumbers;
// Invoke the delegate object.
Console.WriteLine("Invoking the delegate using 'MultiplyNumbers':");
for (int i = 1; i <= 5; i++)
{
d(i, 2);
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
// Declare the associated method.
void MultiplyNumbers(int m, double n)
{
Console.Write(m * n + " ");
}
}
/* Output:
Invoking the delegate using 'MultiplyNumbers':
2 4 6 8 10
*/
在下列範例中,一個委派會同時對應到靜態和執行個體方法,並傳回每個方法的特定資訊。
// Declare a delegate
delegate void Callback();
class SampleClass
{
public void InstanceMethod()
{
Console.WriteLine("A message from the instance method.");
}
static public void StaticMethod()
{
Console.WriteLine("A message from the static method.");
}
}
class TestSampleClass
{
static void Main()
{
var sc = new SampleClass();
// Map the delegate to the instance method:
Callback d = sc.InstanceMethod;
d();
// Map to the static method:
d = SampleClass.StaticMethod;
d();
}
}
/* Output:
A message from the instance method.
A message from the static method.
*/