C#委托的定义方法
在vs中已经内置了用Action和Func进行委托的方法,但是我们用得更多的是delegate来进行委托。下面我把这些委托方法的定义方法的代码在下面列举出来:
Action和Func的用法:Action用于没有返回值的委托,Func用于有返回值的委托。
class Program
{
static void Main(string[] args)
{
//Action用于没有返回值的委托
//没有返回值,没有参数定义的委托
Action action1 = new Action(Method01);
action1();
//没有返回值,但是有参数定义的委托
Action<double> action2 = new Action<double>(Method02);
action2(0.1314);
//Func用于有返回值的委托
//有返回值,没有参数定义的委托
Func<int> func1 = new Func<int>(Method03);
Console.WriteLine(func1());
//有返回值,有参数定义的委托
Func<int, int, bool> func2 = new Func<int, int, bool>(Method04);
Console.WriteLine(func2(2,2));
Console.ReadLine();
}
static void Method01()
{
Console.WriteLine("方法一");
}
static void Method02(double a)
{
Console.WriteLine(a);
}
static int Method03()
{
return 520;
}
static bool Method04(int a, int b)
{
if (a == b)
{
return false;
}
else return true;
}
}
用delegate定义委托来实现委托的四种方法:
//使用delegate进行委托
public delegate void De();
public delegate int De1(int b);
class Program
{
//定义一个委托字段
public De de;
public De1 de1;
static void Main(string[] args)
{
Program Pro = new Program();
//定义方法一:赋值符号右边()里面填和定义的委托同种类型的方法;
Pro.de1 = new De1(Pro.Bb);
Console.WriteLine(Pro.de1(1314));
//定义方法二:可以直接把对象和定义的委托同种类型的方法直接赋值给该委托方法;
Pro.de = Pro.Aa;
Pro.de();
//定义方法三:赋值符号右边的()里面填的是对应的参数个数
Pro.de = delegate ()
{
Console.WriteLine("无返回值无参的委托方法");
};//结束语句需要加一个;
Pro.de();
Pro.de1 = delegate (int b)
{
return b;//带有返回值的委托时,要加return
};
Console.WriteLine(Pro.de1(520));
//定义方法四,使用Lambda表达式,左边是对象的委托,()里面填的是委托对应的参数,{}是方法体,
//有返回值要加return
Pro.de = () =>
{
Console.WriteLine("使用Lambda表达式的无返回值无参数的委托");
};
Pro.de();
Pro.de1 = (int a) =>
{
return a;
};
Console.WriteLine(Pro.de1(1314520));
Console.ReadLine();
}
public void Aa()
{
Console.WriteLine("无返回值无参方法");
}
public int Bb(int b)
{
Console.WriteLine("有返回值有参方法");
return b;
}
}