【问题标题】:Why does this C# function exist in Visual Studio 2015 but not Visual Studio 2017为什么这个 C# 函数存在于 Visual Studio 2015 而不是 Visual Studio 2017
【发布时间】:2017-12-05 02:33:50
【问题描述】:

谁能解释一下为什么这在 Visual Studio 2015 上有效,但在 Visual Studio 2017 上无效?

public static TConvert DynamicPop<TObject, TConvert>(this IEnumerable<TObject> obj, Converter<TObject, TConvert> converter, long @default = 1)
    {
        if (obj.Count() == 0)
        {
            dynamic _defaut = @default;
            return (TConvert)_defaut;
        }
        var collection = obj.ConvertAll<TConvert>(converter);
        collection.Sort();
        dynamic lastValue = collection.Last();
        return (TConvert)(lastValue + 1);
    }

这对我说ConvertAll 不存在。

【问题讨论】:

  • ConvertAll 显然是List&lt;T&gt; 上的一种方法,而不是IEnumerable&lt;T&gt;。也许您在一个环境中拥有另一种环境中不存在的扩展方法?
  • 在VS 2015解决方案中,右键ConvertAll,选择Go To Definition。会发生什么?
  • 鉴于您之前检查过Count()(因此您得到了双重枚举),您应该考虑将IEnumerable&lt;TObject&gt; obj 更改为List&lt;TObject&gt; obj

标签: c# visual-studio visual-studio-2015 visual-studio-2017


【解决方案1】:

在cmets中提到,方法ConvertAll在MSDN上被定义为List&lt;t&gt;的方法,而不是IEnumerable&lt;T&gt;。见here

我无法告诉您为什么这在 Visual Studio 2015 中有效,但您可以轻松地修复代码以使其在 Visual Studio 2017 中有效。只需将转换行更改为:

var collection = obj.ToList().ConvertAll<TConvert>(converter);

请注意,您需要在文件顶部添加using System.Linq;

【讨论】:

    【解决方案2】:

    ConvertAll 不是IEnumerable&lt;T&gt; 上的可用方法。 在 VS 2015 中,您一定是通过您自己构建的(或被引用的)扩展方法调用它。

    一种选择可能是替换:

    var collection = obj.ConvertAll<TConvert>(converter);
    collection.Sort();
    dynamic lastValue = collection.Last();
    

    与:

    dynamic lastValue = obj.Select(z => converter(z)).OrderByDescending(z => z).First();
    

    基本上只是将ConvertAll 替换为Select,它的作用大致相同。 OrderByDescending 也替换了 Sort

    【讨论】:

      猜你喜欢
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      相关资源
      最近更新 更多