我对 c sharp 很陌生。为了掌握关于泛型、回调和扩展方法的概念,我编写了以下示例。我编写的扩展方法将在 IEnumerable 类型上运行,并将接受回调和一个整数参数“year”。它将过滤掉 IEnumerable 并仅返回将通过测试的项目。但是在执行程序时我遇到了一些错误:
The type argument for the extension method can not be inferred from the usage
and for the "return item " inside extension method i am getting error : can not implicitly convert type T to System.Collections.Generic.IEnumerable .An explicit conversion exists.
class Program
{
static void Main(string[] args)
{
List<Students> students = new List<Students>();
students.Add(new Students("zami", 1991));
students.Add(new Students("rahat", 2012));
students.FilterYear((year) =>
{
List<Students> newList = new List<Students>();
foreach (var s in students)
{
if (s.byear >= year)
{
newList.Add(s);
}
}
return newList;
}, 1919);
}
}
public static class LinqExtend
{
public static IEnumerable<T> FilterYear<T>(this IEnumerable<T> source, Func<int, T> callback, int year)
{
var item = callback(year);
return item;
}
}
public class Students
{
public string name;
public int byear;
public Students(string name, int byear)
{
this.name = name;
this.byear = byear;
}
}
最佳答案
根据它在 OP 中的使用方式,假设回调应该返回一个枚举。
扩展方法也有一个问题,它返回单个 T
而不是 IEnumerable<T>
给定函数。
更新扩展方法的回调Func<int, IEnumerable<T>> callback
public static class LinqExtend {
public static IEnumerable<T> FilterYear<T>(this IEnumerable<T> source, Func<int, IEnumerable<T>> callback, int year) {
var items = callback(year);
return items;
}
}
鉴于 OP 中的示例,您似乎也在重新发明现有功能。
您可以使用 LINQ Where
达到相同的结果。
var year = 1919;
var items = students.Where(s => s.byear >= year).ToList();
关于c# - 实现扩展方法来过滤 IEnumerable<T> 会产生一些错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45132002/