你能给我解释一下吗:
- 什么是谓词委托?
- 我们应该在哪里使用谓词?
- 使用谓词时有哪些最佳实践?
描述性源代码将不胜感激。
谓词是一个返回的函数true
or false
。谓词委托是对谓词的引用。
所以基本上谓词委托是对返回的函数的引用true
or 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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)