閱讀目錄
一:委託與線程
二:委託使用的執行個體
三:運行效果
一:委託與線程
.委託基礎
-委託使用的目的:把函數作為參數傳遞
-類似於C++中的函數指標,和函數指標是有區別的:函數指標只能引用靜態方法,而委託可以引用靜態方法,也可以引用執行個體方法,當委託引用執行個體方法時,委託不僅儲存對方法進入點的引用,還儲存對調用該方法的執行個體引用
-是事件處理的基礎
-委託聲明:delegate int MyDelegate (int i); int表示函數傳回型別,MyDelegate表示委託名稱,i表示函數參數
二:委託使用的執行個體
1:聲明委託
delegate int MyDelegate(int i);
2:定義一個靜態方法,返回兩數的乘積
public static int DelegateMethod(int i)
{
return i * i;
}
3:聲明一個委託變數mydelegate,且綁定到靜態方法DelegateMethod
MyDelegate mydelegate = new MyDelegate(DelegateMethod);
執行個體
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _3_DelegateUse
{
class Program
{
//step1聲明委託
public delegate int MyDelegate(int i);
static void Main(string[] args)
{
//step3聲明一個委託變數mydelegate,且綁定到靜態方法DelegateFunction
MyDelegate mydelegate = new MyDelegate(DelegateFunction);
Console.Write("請輸入數字:");
int i = Int32.Parse(Console.ReadLine());
//調用委託方法DelegateFunction
int intResult = mydelegate(i);
Console.WriteLine("結果是:" + intResult);
Console.ReadLine();
}
//step2定義一個靜態方法,返回兩數的乘積
public static int DelegateFunction(int i)
{
return i * i;
}
}
}
三:運行效果