【问题标题】:How do we write a higher order function in this example?在这个例子中我们如何编写一个高阶函数?
【发布时间】:2019-05-06 17:46:05
【问题描述】:

我只是试图传入一个 lambda 函数,该函数会导致一个字符串通常填充一种特殊类型的查找列表。我正在尝试使用高阶函数重写一些代码。问题是Add 方法不喜欢keySelector 函数。下面是代码,请问如何编译:

public static KeyedLookupList<TSource> Slug<TSource>(this List<TSource> items, 
                                                     Func<TSource, string> keySelector)
{
    var keyedLookupList = new KeyedLookupList<TSource>();

    foreach (var item in items)
    {
        keyedLookupList.Add(keySelector, item);
    }

    return keyedLookupList;
}

这里是 Add 方法:

public override void Add(string key, TValue value)
{
    base.Add(new KeyValuePair<string, TValue>(key, value));
}

编译器给出以下错误:

Error   CS1503  Argument 1: cannot convert from 'System.Func<TSource, string>' to 'string'

感谢@peeyush singh 解决:

public static KeyedLookupList<TSource> Slug<TSource>(this List<TSource> items,
        Func<TSource, string> keySelector)
    {
        var keyedLookupList = new KeyedLookupList<TSource>();

        foreach (var item in items)
        {
            keyedLookupList.Add(keySelector(item), item);
        }

        return keyedLookupList;
    }

【问题讨论】:

  • Add()string 作为第一个参数,你试图给它Func&lt;TSource, string&gt;。你想达到什么目的?
  • 您的 add 方法将一个字符串作为第一个参数,您正在向它发送一个 func,这就是编译器所抱怨的。如果您调用添加不是像 Add(keySelector(item), item)
  • TValue valuepublic override void Add(string key, TValue value) 方法中是什么类型的?
  • @CarneyCode 以及KeyValuePairr&lt;string, TValue&gt; 也有string 作为第一个参数(键)......你到底想做什么?我认为您不希望 Func 作为键。
  • @CarneyCode 请阅读我之前的评论。

标签: c# functional-programming


【解决方案1】:

你需要传递被评估的函数,而不是传递函数,就像

keyedLookupList.Add(keySelector(item), item);

【讨论】:

  • 完全正确!我没有在任何地方进行评估。谢谢:)
猜你喜欢
  • 2012-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-11
  • 2017-03-26
相关资源
最近更新 更多