我只是试图传递一个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;
}
除了传递函数,您还需要传递评估后的函数,就像
keyedLookupList.Add(keySelector(item), item);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句