委托的定义:
委托是一个类型,这个类型可以赋值一个方法的引用。如果我们要把方法当作参数来传递的话,就要用到委托。
使用委托的两个阶段:首先定义委托,告诉编译器我们这个委托可以指向哪些类型的方法,然后,创建该委托的实例。
定义委托的语法如下:
delegate void IntMethodInvoker(int x);//有参数,返回类型为void。
这个委托指向方法必须带有一个int类型的参数,并且方法的返回值是void的。
delegate double TwoLongOp(long first,long second);//这个委托指向的方法有两个参数,并且返回值为double类型。
delegate string GetAstring();//指向的方法没有参数,返回值为string。
使用委托:
//示例1:
static void Main(string[] args)
{
int x = 3;
getAstring delgetAstring = new getAstring(x.ToString);
Console.WriteLine(delgetAstring());
Console.ReadKey();
}
delegate string getAstring();
通过委托示例调用方法有两种方式:
delgetAstring();
delgetAstring.Invoke();
//示例2:
private delegate void printString();
static void printStr(printString print)
{
print();
}
static void method1()
{
Console.WriteLine("method10");
}
static void method2()
{
Console.WriteLine("method20");
}
static void Main(string[] args)
{
printString method = method1;
printStr(method);
method = method2;
printStr(method);
Console.ReadKey();
}