【问题标题】:The type arguments for method T cannot be inferred from the usage. Try specifying the type arguments explicitly [duplicate]无法从用法中推断出方法 T 的类型参数。尝试明确指定类型参数 [重复]
【发布时间】:2020-04-30 10:20:29
【问题描述】:

我想为我自己的 GroupBy 编写一个测试,但我遇到了问题。

GroupBy 方法:

GroupBy method.img

我的部分测试代码:

        Func<ProductsList.Product, string> elementSelector = x => x.Name;

        Func<ProductsList.Product, int> keySelector = x => x.Ingredients.Count;

        Func<int, IEnumerable<string>, KeyValuePair<int, IEnumerable<string>>> resultSelector = (IngredientsCount, ProductList) =>
        {

            return new KeyValuePair<int, IEnumerable<string>>(IngredientsCount, ProductList);
        };

        var comparer = new ProductListComparer();

        var result = LinqFunctions.GroupBy(products,
                                            x => keySelector(x),
                                            y => elementSelector(y),
                                            (int IngredientsCount, IEnumerable<string> ProductNames) => resultSelector(IngredientsCount, ProductNames),
                                            comparer
                                            );

       //rest of the code

    }

我收到以下错误:

error CS0411: The type arguments for method 'LinqFunctions.GroupBy<TSource, TKey, TElement, TResult>(IEnumerable<TSource>, Func<TSource, TKey>, Func<TSource, TElement>, Func<TKey, IEnumerable<TElement>, TResult>, IEqualityComparer<TKey>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

我尝试了所有方法,但找不到解决方案。有什么帮助吗?

【问题讨论】:

  • 能否提供LinqFunctions.GroupBy的定义?
  • 我添加了 GroupBy
  • 这是一个自制函数,因为LinqFunctions 不是 LINQ 命名空间。没有看到函数,这个问题无法回答。
  • @Ciprian 在我的回答中看到更新。

标签: c# linq


【解决方案1】:

您可以尝试显式指定类型参数。像这样:

var result = LinqFunctions.GroupBy<ProductsList.Product, int, string, KeyValuePair<int, IEnumerable<string>>>(...

更新。

而且看起来通话应该是这样的:

var result = LinqFunctions.GroupBy(products,
                                        keySelector,
                                        elementSelector,
                                        resultSelector,
                                        comparer
                                        );

所以错误的来源-为resultSelector提供错误的Func

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多