首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 委派基礎:宣告、實例化、呼叫、重新指派完整入門指南

     編輯:關於C語言

委派概念:類型安全的函式指標

C# 透過 System.Delegate 實現函式指標功能。委派封裝方法,包含:

  • 實例方法:物件實例 + 方法
  • 靜態方法:類別 + 靜態方法

委派具備物件導向、型別安全、可靠特性。

三步驟:宣告 → 實例化 → 呼叫

1. 宣告

delegate void myDelegate();                    // 無參數、無回傳
delegate long myDelegate(string mystring);     // 字串參數、長整數回傳

2. 實例化

myDelegate Operation = new myDelegate(methodName);

3. 重新指派

委派物件不可變(簽名固定),但可指向相同簽名的不同方法:

myDelegate Operation = new myDelegate(Add);
Operation = new myDelegate(Multiply); // 簽名相同才可

4. 呼叫

delegate long myDelegate(int i, int j);
myDelegate Operation = new myDelegate(Add);
long lresult = Operation(10, 20); // 像呼叫一般方法

完整示範程式

using System;

public class DelegateClass
{
    delegate long myDelegate(int i, int j);

    public static void Main(string[] args)
    {
        myDelegate Operation = new myDelegate(MathClass.Add);
        Console.WriteLine("Call to Add method through delegate");
        long l = Operation(10, 20);
        Console.WriteLine("Sum of 10 and 20 is " + l);

        Console.WriteLine("Call to Multiply method thru delegate");
        Operation = new myDelegate(MathClass.Multiply);
        l = Operation(1639, 1525);
        Console.WriteLine("1639 multiplied by 1525 equals " + l);
    }
}

public class MathClass
{
    public static long Add(int i, int j) => i + j;
    public static long Multiply(int i, int j) => i * j;
}

輸出:

Call to Add method through delegate
Sum of 10 and 20 is 30
Call to Multiply method through delegate
1639 multiplied by 1525 equals 2499475
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved