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();

}

}

}

 

 

 

委托有返回值的情况

 

 

 

 

 

 

 

 

 

posted @ 2020-06-14 13:12  司徒无名  阅读(205)  评论(0编辑  收藏  举报