声明委托
在C#中使用一个类分两个阶段,首选定义这个类,告诉编译器这个类由什么字段和方法组成的,然后使用这个类实例化对象。在我们使用委托的时候,也需要经过这两个阶段,首先定义委托,告诉编译器我们这个委托可以指向哪些类型的方法,然后,创建该委托的实例。
定义委托的语法如下:
delegate void IntMethodInvoker(int x);
这个委托指向的方法是带有Int类型的参数,且方法返回值为void的,委托名字为IntMethodInvoker
使用委托
实例
private delegate string GetAString();//定义了一个委托类型,这个委托类型的名字叫做GetAString
static void Main(string[] args)
{
int x = 40;
GetAString a = new GetAString(x.ToString);
string s = a();
Console.WriteLine(s);
Console.ReadKey();
}
实例2 使用委托类型作为方法参数
private delegate void PrintString();
static void PrintStr(PrintString)
{
print();
}
static void Method1()
{
Console.WriteLine("Method1");
}
static void Method2()
{
Console.WriteLine("Method2");
}
static void Main(string[] args)
{
PrintString method = Method1;
PrintStr(method);
method = Method2;
PrintStr(method);
Console.ReadKey();
}
Action委托
static void PrintDoubleInt(int i1, int i2)
{
Console.WriteLine(i1+i2)
}
static void Main(string[] args)
{
Action<int,int> a = PrintDoubleInt;
a(34,34);
Console.ReadKey();
}
Func委托
实例1
static void test()
{
return 1;
}
static void Main(string[] args)
{
Func<int> a = test;
Console.WriteLine(a);
Console.ReadKey();
}
实例2
static void test(int i, int j)
{
return i +j;
}
static void Main(string[] args)
{
Func<int,int,int> a = test;
int res = a(1,5);
Console.WriteLine(a);
Console.ReadKey();
}