繁体   English   中英

非静态类中的消费扩展方法

[英]Consume Extension method in non-static class

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

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

这些似乎起作用,因为使用的类是静态的。 有没有办法在如下所示的非静态类中使用扩展方法? 我似乎找不到任何这样的例子。

我有我的扩展方法类:

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;
        }
    }
}

我有上课使用扩展方法

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

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

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

如果我从静态类调用扩展方法,则不会出现“必须在非通用静态类中定义扩展方法”错误:

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);

    }
}

我已经阅读了所有关于非通用静态类错误的所有stackoverflow答案,它们负责编写扩展方法,但不涉及使用它。

因此,问题是:如果无法对非静态类使用扩展方法,那么有什么办法可以类似的方式工作吗? 例如,可以将其称为.ExtensionMethod而不是Helper.ExtensionMethod(passedObject)?

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

这些似乎起作用,因为使用的类是静态的。

不,那是不对的。 绝对不必从静态类或静态方法中使用扩展方法。

但是,必须在以下类中声明它们:

  • 非嵌套
  • 非通用
  • 静态的

当您说:

如果我从静态类调用扩展方法,则不会出现“必须在非通用静态类中定义扩展方法”错误

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM