代码之家  ›  专栏  ›  技术社区  ›  Jonas Elfström

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

  •  8
  • Jonas Elfström  · 技术社区  · 16 年前

    我认为在C 3.0中,不可能使用运算符作为方法的参数,但是是否有一种方法可以模拟这种方法,或者使用某种语法上的糖分,使它看起来像是正在发生的事情?

    我问是因为我最近实施了 the thrush combinator in C# 但是在翻译的时候 Raganwald's Ruby example

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

    上面写着“取1到100之间的数字,保留奇数,取其和,然后回答该数字的平方。”

    我没赶上 Symbol#to_proc 东西。这就是 select(&:odd?) 以及 inject(&:+) 上面。

    2 回复  |  直到 16 年前
        1
  •  8
  •   Jon Skeet    16 年前

    简单来说,你可以只用一个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
         }
    }
    

    事实上,马克·格雷弗 done something very similar 在里面 MiscUtil ,如果你想看的话。然后你可以打电话给:

    DoSomething(Operator<int>.Plus);
    

    它并不完全漂亮,但我相信它是目前最受支持的。

    恐怕我真的不懂红宝石的东西,所以我不能对此发表评论…

        2
  •  2
  •   Pavel Minaev    16 年前

    以下是直接的、直译的(尽可能多的)C翻译:

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

    明确地:

    • 阻碍: {||} -成为羔羊: =>
    • select 变成 Where
    • inject 变成 Aggregate
    • into 成为lambda实例的直接调用