c# - 实现扩展方法来过滤 IEnumerable<T> 会产生一些错误

标签 c# generics ienumerable extension-methods

我对 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/

相关文章:

c# - 来自 IEnumerable 的 foreach 中特定类型的对象

typescript - 如何使这个通用 TypeScript 函数按预期工作?

c# - 为什么不能克隆 IEnumerator?

c# - 如何在嵌套字典上实现 IEnumerable<T>?

javascript - m 未定义 - 在三列上排序时的 sorttable.js

java - 如何将 Jackson 与运行时泛型一起使用?

C# 对象或数组

c# - 将 T[] 转换为 IList<T> 有什么注意事项吗?

c# - vb6 与 c# 中的异或 (XOR)

c# - 关于使用 F# 创建可从 C# 使用的 Matrix 程序集