C# 中作为方法参数的运算符
我认为不可能在 C# 3.0 中使用运算符作为方法的参数,但是有没有办法模拟它或使用一些语法糖使其看起来像是正在发生的事情?
我问这个问题是因为我最近在 C# 中实现了画眉组合器 但在翻译Raganwald 的 Ruby 示例
(1..100).select(&:odd?).inject(&:+).into { |x| x * x }
其内容为“取出 1 到 100 之间的数字,保留奇数,将这些数字相加,然后计算该数字的平方。”
我对 Symbol#to_proc 的内容感到不满意。这就是上面 select(&:odd?)
和 inject(&:+)
中的 &: 。
I don't think it's possible to use operators as a parameters to methods in C# 3.0 but is there a way to emulate that or some syntactic sugar that makes it seem like that's what's going on?
I ask because I recently implemented the thrush combinator in C# but while translating Raganwald's Ruby example
(1..100).select(&:odd?).inject(&:+).into { |x| x * x }
Which reads "Take the numbers from 1 to 100, keep the odd ones, take the sum of those, and then answer the square of that number."
I fell short on the Symbol#to_proc stuff. That's the &: in the select(&:odd?)
and the inject(&:+)
above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯,简单来说,您可以只使用 lambda:
但这并不是很令人兴奋。如果能为我们预先构建所有这些代表,那就太好了。当然,您可以使用静态类来做到这一点:
事实上,Marc Gravell 已经完成了 如果您想查看,MiscUtil 中的内容非常相似。然后你可以调用:
它并不完全漂亮,但我相信它是目前支持的最接近的。
恐怕我真的不懂 Ruby 的东西,所以我无法对此发表评论......
Well, in simple terms you can just use a lambda:
That's not very exciting though. It would be nice to have all those delegates prebuilt for us. Of course you could do this with a static class:
Indeed, Marc Gravell has done something very similar in MiscUtil, if you want to look. You could then call:
It's not exactly pretty, but it's the closest that's supported at the moment, I believe.
I'm afraid I really don't understand the Ruby stuff, so I can't comment on that...
以下是直接的、字面的(尽可能多的)C# 翻译:
具体来说:
{||}
- 成为 lambda:=>
select 变为
Where
inject
变为Aggregate
into
变为对 lambda 实例的直接调用The following is direct, literal (as much as possible) C# translation:
Specifically:
{||}
- become lambdas:=>
select
becomesWhere
inject
becomesAggregate
into
becomes a direct call on a lambda instance