使用非静态 class 中的扩展方法

Consume Extension method in non-static class

我见过的所有扩展方法示例都在 class 中使用扩展方法,例如:

class Program
{
    static void Main()
    {
        ...Call extension method here
    }
}

这些似乎有效,因为消费 class 是静态的。有没有办法像下面这样在非静态 class 中使用扩展方法?我似乎找不到这样的例子。

我有我的扩展方法class:

using System;
using System.Collections.Generic;

namespace AwesomeApp
{
    public static class LinqExtensionMethods
    {
        public static IEnumerable<T> FindItemsBeforeAndAfter<T>(this IEnumerable<T> items, Predicate<T> matchFilling)
        {
            if (items == null)
                throw new ArgumentNullException("items");
            if (matchFilling == null)
                throw new ArgumentNullException("matchFilling");
            return items;
        }
    }
}

我有我的 class 使用扩展方法

namespace AwesomeApp
{
    public class Leaders : ILeaders
    {
        var leaders = GetAllLeaders();

        var orderedleaders = leaders.OrderByDescending(o => o.PointsEarned);

        var test = orderedleaders.FindItemsBeforeAndAfter(w => w.UserId == 1);
    }
}

如果我从静态 class 调用扩展方法,我不会 'Extension method must be defined in a non-generic static class' 错误:

public class test
{
    public void testfunc()
    {
        List<int> testlist = new List<int>() {1,2,3,4,5,6,7,8,9};

        testlist.FindItemsBeforeAndAfter<int>(e => e == 5);

    }
}

我已经通读了所有关于非通用静态 class 错误的 Whosebug 答案,它们处理编写您的扩展方法但不处理使用它。

所以问题是:如果无法使用具有非静态 class 的扩展方法,那么有什么方法可以以类似的方式工作吗?例如它可以被称为 .ExtensionMethod 而不是 Helper.ExtensionMethod(passedObject)??

解决方案: 我想我从 public class Leaders : ILeaders 剪切并粘贴了扩展方法到它自己的 class 这样我可以将其设为静态,但实际上我只是复制了它。编译器错误指向 class 名称,因此我没有在文件底部看到扩展方法。错误消息是准确的,每个回答都是正确的。

These seem to work because the consuming class is static.

不,这是不正确的。扩展方法绝对不必从静态 classes 或静态方法 consumed

但是,它们必须在 class 中 声明,即:

  • 非嵌套
  • 非通用
  • 静态

您似乎混淆了调用和声明 - 当您说:

If I call the extension method from a static class I do not the the 'Extension method must be defined in a non-generic static class' error

...只有当您尝试 声明 不满足上述所有条件的 class 中的方法时,您才会得到它。您应该双击错误以显示它的生成位置 - 我相信您会发现它是声明,而不是方法的使用。

请注意,您的最后一个示例 (class test) 不是 静态 class,也不是静态方法。