这个例子纯粹是为了学习,否则我会立刻使用Lambda表达式.
我想尝试使用没有lambda的Where()扩展方法只是为了看看它看起来如何,但我无法弄清楚如何让它编译和正常工作.这个例子毫无意义,所以不要试图找出任何逻辑.
我基本上只是想知道是否可以使用扩展方法而不使用lambda(仅用于学习目的)以及在代码中的外观.
我感到困惑的是Where()条件接受a Func<int,bool>,但该方法返回一个IEnumerable<int>?定义Func的方式,它接受一个int并返回一个bool.如果是这样的话对我来说会更有意义Func<int, bool, IEnumberable<string>>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Delegates
{
public class Learning
{
/// <summary>
/// Predicates - specialized verison of Func
/// </summary>
public static void Main()
{
List<int> list = new List<int> { 1, 2, 3 };
Func<int, bool> someFunc = greaterThanTwo;
IEnumerable<int> result = list.Where(someFunc.Invoke(1));
}
static IEnumerable<int> greaterThanTwo(int arg, bool isValid)
{
return new List<int>() { 1 };
}
}
}
Run Code Online (Sandbox Code Playgroud)
更新的代码
public class Learning
{
/// <summary>
/// Predicates - specialized verison of Func
/// </summary>
public static void Main()
{
// Without lambda
List<int> list = new List<int> { 1, 2, 3 };
Func<int, bool> someFunc = greaterThanTwo;
// predicate of type int
IEnumerable<int> result = list.Where(someFunc);
}
static bool greaterThanTwo(int arg, bool isValid)
{
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
'greaterThanTwo'没有重载匹配委托'System.Func'
Where采用一个接受单个元素(在本例中为int)作为参数的函数,以及一个布尔值作为其返回类型.这被称为谓词 - 它给出了"是"或"否"的答案,可以反复应用于相同类型的元素序列.
你在这个greaterThanTwo函数上出错了- 它需要两个参数,而不是一个 - 然后返回一个IEnumerable<int>- 所以它完全不兼容Func<int, bool>.它应该采取int并返回bool- 再次,这是一个谓词(见上文).
一旦你解决了这个问题,你的另一个问题是Invoke- 你没有调用任何东西 - 你将一个委托(指针)交给一个方法,而内部的内部Where将在需要时负责调用它.
试试这个:
static bool greaterThanTwo(int arg)
{
return (arg > 2);
}
//snip
Func<int, bool> someFunc = greaterThanTwo;
IEnumerable<int> result = list.Where(someFunc);
Run Code Online (Sandbox Code Playgroud)