【发布时间】:2011-05-25 07:22:15
【问题描述】:
这个例子纯粹是为了学习,否则我会马上使用 Lambda 表达式。
我想尝试在没有 lambda 的情况下使用 Where() 扩展方法,只是为了看看它的外观,但我不知道如何让它编译和正常工作。这个例子没有任何意义,所以不要费心去弄清楚它的任何逻辑。
我基本上只是想知道是否可以在不使用 lambda 的情况下使用扩展方法(仅用于学习目的)以及在代码中的样子。
我感到困惑的是 Where() 条件接受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 };
}
}
}
更新代码
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;
}
}
我收到以下错误:
“greaterThanTwo”没有重载匹配委托“System.Func”
【问题讨论】:
-
从 MSDN 查看这篇文章。 msdn.microsoft.com/en-us/library/bb534803.aspx
-
如果您更新您的方法签名以匹配 Func 的委托语法,您也许可以通过这种方式传递它。