谓词是返回true
或false
的函数.谓词委托是对谓词的引用.
基本上,谓词委托是对返回true
或false
的函数的引用.谓词对于筛选值列表非常有用——下面是一个例子.
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以更简洁的方式表示谓词:
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);
}
}