【发布时间】: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<TSource, string>。你想达到什么目的? -
您的 add 方法将一个字符串作为第一个参数,您正在向它发送一个 func,这就是编译器所抱怨的。如果您调用添加不是像 Add(keySelector(item), item)
-
TValue value在public override void Add(string key, TValue value)方法中是什么类型的? -
@CarneyCode 以及
KeyValuePairr<string, TValue>也有string作为第一个参数(键)......你到底想做什么?我认为您不希望Func作为键。 -
@CarneyCode 请阅读我之前的评论。