【发布时间】:2015-10-21 03:00:39
【问题描述】:
通过使用委托,我希望使用以下代码将 IEnumerable 项目中的数字 5 打印到屏幕上;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using extended;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
IEnumerable<int> cities = new[] { 1, 2, 3, 4, 5 };
IEnumerable<int> query = cities.StartsWith(hello);
foreach (var item in query)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
static int hello(int x)
{
return x > 4 ? x : 0;
}
}
}
namespace extended
{
public static class A
{
public static IEnumerable<T> StartsWith<T>(this IEnumerable<T> input, inputdelegate<T> predicate)
{
foreach (var item in input)
{
if (item.Equals(predicate))
{
yield return item;
}
}
}
public delegate int inputdelegate<T>(T input);
}
}
代码编译没有任何错误,但没有在屏幕上显示输出。知道我哪里可能出错了吗?
【问题讨论】:
-
if (item.Equals(predicate))始终为假。你的意图是什么? -
@AlexD 在 {1,2,3,4,5} 谓词 = 5 和
foreach (var item in input)中的数字 5 上,当循环迭代到项目 5 时,(item.Equals(predicate))应该返回 true? -
@RehanKhan 我在下面的答案中为您的源代码提供了一些修复,这些修复会产生您正在寻找的内容。祝你好运!
-
我猜谓词应该是
bool,返回true的值是5,然后被调用为if(predicate(item)){yield return item;}。