Func和Action委托的区别和简单使用

Func和Action委托的区别和简单使用


1、两种委托的常见形式和区别
(1)、Func委托有5个重载形式,区别仅在于它所指向的方法的签名的参数个数,分别如下:

Func<TResult>

Func<T,TResult>

Func<T1,T2,TResult>

Func<T1,T2,T3,TResult>

Func<T1,T2,T3,T4,TResult>
其中T,T1,..T4是委托指向的方法的参数的类型,TResult为方法的返回类型。

(2)、Action委托也有5个重载形式,分别如下:
Action

Action<T>

Action<T1,T2>

Action<T1,T2,T3>

Action<T1,T2,T3,T4>
其中T,T1,..T4是委托指向的方法的参数的类型。


从上面的委托形式我们就可以分析出来,Func和Action委托的唯一区别在于Func要有返回值, Action没有返回值。

2、简单示例代码

class Program
{
static void Main( string [] args)
{
int num = 5 ;

FirstCalcSquare calFirst = Square; // delegate
Console.WriteLine( " The square of {0} is {1}. " , num, calFirst(num));

Func < int , int > funcTest = Program.Square; // Func
Console.WriteLine( " The square of {0} is {1}. " , num, funcTest(num));

SecondCalcSquare calSecond = GetSquere;
calSecond(num); // delegate

Action < int > actionTest = Program.GetSquere;
actionTest(num); // Action

Console.ReadLine();
}
private delegate int FirstCalcSquare( int input);
private static int Square( int input)
{
return input * input;
}

private delegate void SecondCalcSquare( int input);
private static void GetSquere( int input)
{
Console.WriteLine( " The square of {0} is {1}. " , input, input * input);
}
}
引自:http://www.cnblogs.com/jeffwongishandsome/archive/2010/04/08/1512556.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值