[英]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));
But I get an error that says that the delete System.Func does not take 1 argument. 但是我收到一条错误消息,指出delete System.Func不接受1参数。
However, if I use a predicate intead of the function, it works. 但是,如果我使用该函数的谓词inadad,它就可以工作。
What am I missing? 我想念什么?
thank so much. 非常感谢。
You need Func<T,bool>
(which takes one argument and returns bool
), not Func<T,T,bool>
您需要Func<T,bool>
(需要一个参数并返回bool
),而不是Func<T,T,bool>
Predicate<T>
works because it takes one argument and returns bool
, so it matches with the lambda expression . Predicate<T>
之所以起作用,是因为它接受一个参数并返回bool
,因此它与lambda表达式匹配。 Func<T,T,bool>
expects two arguments and returns bool which doesn't match with your expression hence the error. Func<T,T,bool>
需要两个参数并返回与您的表达式不匹配的布尔值,因此是错误。
Your Func<T,T,bool>
takes 2 parameters and returns bool
您的Func<T,T,bool>
接受2个参数并返回bool
You have two choise 你有两个选择
Func<T,bool>
如Selman22所说,将其更改为Func<T,bool>
(e1,e2) => ..
称它为(e1,e2) => ..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.