繁体   English   中英

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

[英]Operators as method parameters in 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<int, int, int> op)
{
    Console.WriteLine(op(5, 2));
}

DoSomething((x, y) => x + y);
DoSomething((x, y) => x * y);
// etc

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

public static class Operator<T>
{
     public static readonly Func<T, T, T> Plus;
     public static readonly Func<T, T, T> Minus;
     // etc

     static Operator()
     {
         // Build the delegates using expression trees, probably
     }
}

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

DoSomething(Operator<int>.Plus);

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

我担心我真的不理解Ruby的东西,所以我不能对此发表评论......

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

(Func<int>)(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实例的直接调用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM