如何在扩展方法中使用函数作为参数? [英] how to use a function as parameter in extension method?
问题描述
我已阅读建议在扩展方法中使用函数而不是谓词,因此我正在尝试这样做.
I have read that is recomended to use functions instead of predicates in the extension methods, so I am trying to do it.
public static void Insert<T>(this ObservableCollection<T> paramOC, T NewElement, Func<T, T, bool> condition)
{
//code
}
我正试图以这种方式使用:
I am trying to use in this way:
myOC.Insert(myNewElement, e=>e.Name.CompareTo(myNewElement.Name) > 0));
但是我收到一条错误消息,指出delete System.Func不带1个参数.
But I get an error that says that the delete System.Func does not take 1 argument.
但是,如果我使用该函数的谓词inadad,它将起作用.
However, if I use a predicate intead of the function, it works.
我想念什么?
非常感谢.
推荐答案
您需要Func<T,bool>
(需要一个参数并返回bool
),而不是Func<T,T,bool>
You need Func<T,bool>
(which takes one argument and returns bool
), not Func<T,T,bool>
Predicate<T>
之所以有效,是因为它接受一个参数并返回bool
,因此它与 lambda表达式匹配.Func<T,T,bool>
需要两个参数并返回与表达式不匹配的布尔值因此是错误.
Predicate<T>
works because it takes one argument and returns bool
, so it matches with the lambda expression.Func<T,T,bool>
expects two arguments and returns bool which doesn't match with your expression hence the error.
这篇关于如何在扩展方法中使用函数作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!