【问题标题】:Calling an extension method statically throws MissingMethodException [closed]静态调用扩展方法会引发 MissingMethodException [关闭]
【发布时间】:2014-12-15 10:14:29
【问题描述】:

我有一个扩展方法,可以将一组项目分成更小的子集:

static class MyClass {
    /// <summary>
    /// Breaks a list of items into chunks of a specific size
    /// </summary>
    public static IEnumerable<IEnumerable<T>> chunk<T>(this IEnumerable<T> source, int chunksize)
    {
        while (source.Any())
        {
            yield return source.Take(chunksize);
            source = source.Skip(chunksize);
        }
    }
}

现在我可以通过

调用这个方法
  • MyClass.chunk(myEnumerable, 500),或使用
  • myEnumerable.chunk(200)

对吗?但是当我使用静态(第一个)调用时,我的一个客户抱怨 MissingMethodException

System.MissingMethodException:找不到方法:System.Collections.Generic.List´1&lt;System.Collections.Generic.List´1&lt;!!0&gt;&gt; MyClass.chunk(System.Collections.Generic.IEnumerable´1&lt;!!0&gt;, Int32).)。

我无法复制它,也许在你的帮助下我可以......

【问题讨论】:

  • 我认为这是dll问题而不是逻辑问题,请确保用户在正确的位置部署了最新的dll
  • 两种调用方式没有区别,前者只是后者的语法糖。如果您的客户遇到缺少方法的异常,则表明他的代码正在针对没有该方法的旧版本 DLL 执行,但正在针对具有该方法的新版本进行编译。
  • @stakx 我不想要奇迹,我只是想知道我之前如何重现这个问题,所以我可以提供一些进一步的信息。不过你的回答已经给了我一些提示。

标签: c# .net extension-methods missingmethodexception


【解决方案1】:

您是否注意到您的方法返回 IEnumerable&lt;IEnumerable&lt;T&gt;,但错误消息是在谈论返回 List&lt;List&lt;T&gt;&gt; 的方法?

如果我不得不猜测,我会说您在某个时候更改了扩展方法的返回类型。然后,您只替换了包含您的扩展方法的 DLL,而现在其他一些依赖的 DLL 正试图像以前一样调用您的扩展方法……但它当然不再存在了。

您必须重新编译和重新部署所有引用/调用您的扩展方法的程序集。

P.S.:无论您是通过MyClass.chunk(myEnumerable, 500) 还是通过myEnumerable.chunk(200) 调用扩展方法都没有任何区别;后一种调用扩展方法的方式是前者的语法快捷方式,C#编译器会自动将扩展方法调用转换为静态方法调用。

【讨论】:

  • 显然这是一些没有更新的旧库的问题。实际上,该方法的返回类型之前是 List 并且已更改为 IEnumerable。感谢您的帮助
猜你喜欢
  • 2011-06-06
  • 2015-08-12
  • 1970-01-01
  • 1970-01-01
  • 2011-05-29
  • 2012-11-22
  • 1970-01-01
  • 1970-01-01
  • 2010-10-26
相关资源
最近更新 更多