运算符作为C#中的方法参数

我不认为使用运算符作为C#3.0中方法的参数是可能的,但有没有办法模拟那个或一些语法糖,使它看起来像是在发生什么?

我问,因为我最近在C#中实现了鹅口疮组合,但是在翻译Raganwald的Ruby例子时

(1..100).select(&:odd?).inject(&:+).into { |x| x * x } 

其中写着“从1到100取数字,保留奇数,取这些数字的总和,然后回答那个数字的平方。”

我对Symbol#to_proc的东西不满意 。 这是&:在select(&:odd?)和上面的inject(&:+)

好吧,简单来说你可以使用lambda:

 public void DoSomething(Func op) { Console.WriteLine(op(5, 2)); } DoSomething((x, y) => x + y); DoSomething((x, y) => x * y); // etc 

但这并不是很令人兴奋。 让我们为这些代表预先建立所有代表会很高兴。 当然你可以用静态类做到这一点:

 public static class Operator { public static readonly Func Plus; public static readonly Func Minus; // etc static Operator() { // Build the delegates using expression trees, probably } } 

事实上,如果你想看的话,Marc Gravell在MiscUtil中 做了类似的事情 。 然后你可以打电话:

 DoSomething(Operator.Plus); 

它不是很漂亮,但我相信它是目前支持的最接近的。

我担心我真的不懂Ruby的东西,所以我不能对此发表评论……

以下是直接,字面(尽可能)C#翻译:

 (Func)(x => x * x)( Enumerable.Range(1, 100) .Where(x => x % 2 == 1) .Aggregate((x, y) => x + y)) 

特别:

  • blocks: {||} – 成为lambdas: =>
  • select成为Where
  • inject成为Aggregate
  • into成为对lambda实例的直接调用