如何将附加参数传递给谓词函数?
我可以将附加参数传递给谓词函数吗?
我实际上在排序过程中需要它。
public void Sort(
Comparison<T> comparison
)
我想以这种形式使用 Comparison
谓词:
public delegate int Comparison<T>(
T x,
T y,
object extraParameter
)
这可能吗?
Can I pass additional parameters to a predicate function?
I need it in a sorting process actually.
public void Sort(
Comparison<T> comparison
)
where I would like to use the Comparison
predicate in this form:
public delegate int Comparison<T>(
T x,
T y,
object extraParameter
)
Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,但你可以这样做:
No, but you can do this:
声明谓词时简单捕获所需的变量。例如:
Simple capture the variables you need when you declare the predicate. Eg:
参加聚会有点晚了,所以我回答这个问题,以防有人通过谷歌搜索发现这里(就像我所做的那样)。
您不能传递多个参数,但您可以采取一些技巧来避开该限制:
使谓词需要 Tuple (或值元组),这样您可以通过创建元组并将其传递给谓词来传递更多值。据我所知,最大的元组最多有 3 个参数,但如果您需要传递更多参数,您可以轻松创建自己的元组。
Edit1:我建议这样做而不是上面的答案的原因是,有时您没有直接声明谓词,而是使用返回 bool 作为谓词的方法。
例如:
A bit late to the party so i am answering this in case anyone comes across here by a google search (as i did).
You cannot pass more than parameter but you can do a trick to dodge that limitation:
Make it so the predicate requires a Tuple (or value tuple), that way you can pass more values by creating the tuple and passing it to the predicate. As far as i know the biggest tuple has a maximum of 3 parameters, but you can easily create your own tuples if you need to pass more parameters.
Edit1: The reason i suggested this instead of the above answers is that sometimes you are not declaring the predicate directly and instead using a method that returns bool as the predicate.
E.g: