1. 程式人生 > WINDOWS開發 >C#委託的學習筆記

C#委託的學習筆記

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

?

namespace delegateExample

{

delegate void MyDel(int value); //定義委託

//delegate ---關鍵字Keyword

//void---返回型別Return type

//Delegate type name

//int--簽名Signature,翻譯簽名是計算機領域的錯誤翻譯,這種應該就是"型別特徵""變數型別"

//value--變數名

//委託與類的區別:

//1,以delegate關鍵字開頭2,沒有方法主體:沒有方法主體肯定要想辦法實現它呀。埋坑,就會有多重情況的實現。

//結論:這個委託型別,只接受 沒有返回值void,並且有單個int引數的方法(或叫做函式);

// ②委託型別,就是自定義了一個函式的指標,就是看上去像類,用new一下,裡面接受的是函式,如new MyDel(PrintLow);

class Program

{

static void Main(string[] args)

{

void PrintLow(int value) //嵌套了函式PrintLow

{

Console.WriteLine($"{ value }");

}

?

MyDel delegateLow; //宣告委託變數 Declare delegate variable.

delegateLow = new MyDel(PrintLow);//

例項化一下

?

delegateLow(10);

?

?

//一步到位例項化

MyDel delegateLow2 = new MyDel(PrintLow);

delegateLow2(10000);

?

Console.ReadKey();

}

}

}

?

技術分享圖片

?

?

?

?

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

?

namespace delegateExample02

{

// Define a delegate type with no return value and no parameters.

//定義一個委託型別,沒有返回值 void 也沒有 引數(),也即沒有返回值,也沒有引數的函式指標

delegate void PrintFunction();

?

class Test

{

public void Print1()

{

Console.WriteLine("Print1 -- instance");

}

?

public static void Print2()

{

Console.WriteLine("Print2 -- static");

}

}

class Program

{

static void Main(string[] args)

{

Test t = new Test(); // Create a test class instance.

PrintFunction pf; // Create a null delegate.

pf = t.Print1; // Instantiate and initialize the delegate.指標關聯到類Test的例項t的方法Print1

// Add three more methods to the delegate.

pf += Test.Print2; //函式指標繼續關聯靜態方法Print2

pf += t.Print1;//繼續關聯tPrint1

pf += Test.Print2; // The delegate now contains four methods.繼續,此時,已經關聯了4個函數了(裡面包含了重複)

if (null != pf) // Make sure the delegate isn‘t null.

pf(); // Invoke the delegate.

else

Console.WriteLine("Delegate is empty");

Console.ReadKey();

}

}

}

?

?

技術分享圖片

?

?

?

?

?

?

?

?

?

?

?