我只是想传递一个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;
}
答案 0 :(得分:2)
代替传递函数,您需要传递经过评估的函数,就像
ExtensionlessUrlHandler-Integrated-4.0