在C#predicate代表 [英] Predicate Delegates in C#

查看:570
本文介绍了在C#predicate代表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以给我解释一下;

Can you explain me;

  • 什么是predicate代表?
  • 我们应该在哪里使用predicates?
  • 约predicates任何的最佳做法?

描述源$ C ​​$ C将AP preciated,

Descriptive source code will be appreciated,

感谢所有答复!

推荐答案

一个predicate是一个函数,返回。一个predicate委托是一个引用predicate。

A predicate is a function that returns true or false. A predicate delegate is a reference to a predicate.

所以基本上是predicate委托是一个引用函数,返回。 predicates是用于过滤值的列​​表非常有用的 - 这里就是一个例子。

So basically a predicate delegate is a reference to a function that returns true or false. Predicates are very useful for filtering a list of values - here is an example.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
    	List<int> list = new List<int> { 1, 2, 3 };

    	Predicate<int> predicate = new Predicate<int>(greaterThanTwo);

    	List<int> newList = list.FindAll(predicate);
    }

    static bool greaterThanTwo(int arg)
    {
    	return arg > 2;
    }
}

现在,如果你使用的是C#3你可以使用lambda重新present的predicate在一个更清洁的方式:

Now if you are using C# 3 you can use a lambda to represent the predicate in a cleaner fashion:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
    	List<int> list = new List<int> { 1, 2, 3 };

    	List<int> newList = list.FindAll(i => i > 2);
    }
}

这篇关于在C#predicate代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆