您的位置:首页 > 编程语言 > C#

C#委托:Predicate<>、 Func<> 、 Action<>的简单理解

2017-06-10 16:37 477 查看
Predicate

使用前

namespace Read
{
public delegate void GetShowMember(int[] num);
class Program
{
public static void Main(string[] args)
{
var arr = new int[] { 1, 2, 3, 4, 65, 4, 3, 2, 25, 15123, 53 };
//使用正常的委托方法  委托是一种类型,需要创建实例
var DelShow = new GetShowMember(ShowMember);
DelShow(arr);
Console.ReadKey();
}

public static bool ShowMember(int[] number)
{
bool ret = false;
Console.WriteLine(string.Join(",", number));
return ret;
}
}


使用后:

    

//Predict 委托表示的方法传入一个类型参数,返回值必须是bool类型;
var DelPredictShow = new Predicate<int[]>(ShowMember );
DelPredictShow(arr);


//等价于
Predicate<int[]> show = ShowMember;
show(arr);


Func:

使用前

namespace Read
{
public delegate int GetMax(int[] num);
class Program
{
public static void Main(string[] args)
{

int[] in1 = { 10, 2, 73, 94, 65, 49, 399, 2, 25, 151, 23, 53 };
var arr = new int[] { 1, 2, 3, 4, 65, 4, 3, 2, 25, 15123, 53 };
//使用委托
var DelGetMax = new GetMax(GetMaxNum);
DelGetMax(arr);
DelGetMax(in1);
Console.ReadKey();
}
public static int GetMaxNum(int[] number)
{
int max = number[0];
foreach (var item in number)
{
if (max < item)
max = item;
}
Console.WriteLine("Get the Max {0}", max);
return max;
}
}
}


使用后

 

//<int[],int>后面是返回值,前面是参数,参数可以有0~16个,返回值必须有一个
var FuncGetMax = new Func<int[], int>(GetMaxNum );
FuncGetMax(in1);
FuncGetMax(arr);


//等价于
Func<int[], int> func = GetMaxNum;
func(in1);
func(arr);


Action使用前

namespace Read
{
public delegate void ShowMember(int[] num);
class Program
{
public static void Main(string[] args)
{

int[] in1 = { 10, 2, 73, 94, 65, 49, 399, 2, 25, 151, 23, 53 };

var DelShowMember = new ShowMember(ShowMemberOfNumber);
DelShowMember(in1);

Console.ReadKey();
}

public static void ShowMemberOfNumber(int[] number)
{
Console.WriteLine("Show the member of the array");
Console.WriteLine(string.Join(",", number));
}
}
}


使用后:

//<int[]>为参数,可以有0~16个,没有返回值
var DelActionShow = new Action<int[]>(ShowMemberOfNumber );
DelActionShow(in1);

//等价于
Action<int[]> action = ShowMemberOfNumber;
action(in1);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: