Jon*_*röm 8 c# ruby lambda extension-methods
我不认为使用运算符作为C#3.0中方法的参数是可能的,但有没有办法模拟它或某些语法糖,使它看起来像是在发生什么?
我问,因为我最近在C#中实现了画眉组合,但在翻译Raganwald的Ruby示例时
(1..100).select(&:odd?).inject(&:+).into { |x| x * x }
Run Code Online (Sandbox Code Playgroud)
其中写着"从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
Run Code Online (Sandbox Code Playgroud)
但这并不是很令人兴奋.让所有这些代表为我们预建的会很高兴.当然你可以用静态类做到这一点:
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
}
}
Run Code Online (Sandbox Code Playgroud)
事实上,如果你想看的话,Marc Gravell 在MiscUtil中做了类似的事情.然后你可以打电话:
DoSomething(Operator<int>.Plus);
Run Code Online (Sandbox Code Playgroud)
它不是很漂亮,但我相信它是目前支持的最接近的.
我担心我真的不理解Ruby的东西,所以我不能对此发表评论......