簡體   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