NewLanguageFeatures-lambda表达式使用n重要性
我正在研究 lambda 表达式和 lambda 表达式的概念。扩展方法:-
namespace NewLanguageFeatures
{
public delegate bool KeyValuePair<K, V>(K key, V value);
/// <summary>
/// Task 13 – Calling a Complex Extension Method using Lambda Expressions [ops]
/// </summary>
public static class LambdaExtensions
{
//This extension method takes in a dictionary and a delegate
public static List<K> FilterBy<K, V>(
this Dictionary<K, V> items,
KeyValueFilter<K, V> filter)
{
var result = new List<K>();
foreach (KeyValuePair<K, V> element in items)
{
if (filter(element.Key, element.Value))
result.Add(element.Key);
}
return result;
}
}
}
它给出以下错误:
Error 1 Cannot convert type 'System.Collections.Generic.KeyValuePair<K,V>' to 'NewLanguageFeatures.KeyValuePair<K,V>' and
Error 2 'NewLanguageFeatures.KeyValuePair<K,V>' does not contain a definition for 'Key' and no extension method 'Key' accepting a first argument of type 'NewLanguageFeatures.KeyValuePair<K,V>' could be found (are you missing a using directive or an assembly reference?)
有什么想法可以解决吗?
I was going through the concepts of lambda expression & extension methods :-
namespace NewLanguageFeatures
{
public delegate bool KeyValuePair<K, V>(K key, V value);
/// <summary>
/// Task 13 – Calling a Complex Extension Method using Lambda Expressions [ops]
/// </summary>
public static class LambdaExtensions
{
//This extension method takes in a dictionary and a delegate
public static List<K> FilterBy<K, V>(
this Dictionary<K, V> items,
KeyValueFilter<K, V> filter)
{
var result = new List<K>();
foreach (KeyValuePair<K, V> element in items)
{
if (filter(element.Key, element.Value))
result.Add(element.Key);
}
return result;
}
}
}
its giving following error:
Error 1 Cannot convert type 'System.Collections.Generic.KeyValuePair<K,V>' to 'NewLanguageFeatures.KeyValuePair<K,V>' and
Error 2 'NewLanguageFeatures.KeyValuePair<K,V>' does not contain a definition for 'Key' and no extension method 'Key' accepting a first argument of type 'NewLanguageFeatures.KeyValuePair<K,V>' could be found (are you missing a using directive or an assembly reference?)
any ideas to reslove?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这只是你的代码中的一个拼写错误:
应该是
,然后它就可以工作了。
然而,
Func
会做同样的事情,而不需要额外的定义。最后,使用var
(即foreach(var element in items)
可以避免其中一个冲突。不过说实话,现有的
Where
做了这么多,以至于我不会费心去定义它 - 即This is just a typo in your code:
should surely be
and then it works.
However, a
Func<K,V,bool>
would do the same thing, without needing the extra definition. Finally, usingvar
(i.e.foreach(var element in items)
would have avoided one of the conflicts.To be honest, though, the existing
Where
does so much of this that I wouldn't bother defining this - i.e.