正确的柯里在C# [英] Proper Currying in C#

查看:117
本文介绍了正确的柯里在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于的DoSomething 的方法,需要一个(无参数)的功能和处理它以某种方式。 ?有没有更好的方法来与参数比下面的代码片段创建功能重载

 公共静态TResult DoSomething的< TResult> (Func键< TResult> FUNC)
{
//调用FUNC()和做其他的事情
}

公共静态TResult DoSomething的< T0,TResult>(
Func键< T0,TResult> FUNC,
T0为arg0)
{
返回DoSomething的(()=> FUNC(arg0中));
}

公共静态TResult DoSomething的< T0,T1,TResult>(
Func键< T0,T1,TResult> FUNC,
T0为arg0,T1 ARG1)
{
返回DoSomething的(ARG => FUNC(阿根廷,ARG1),为arg0);
}

公共静态TResult DoSomething的< T0,T1,T2,TResult>(
Func键< T0,T1,T2,TResult> FUNC,
T0为arg0, ARG1 T1,T2 ARG2)
{
返回DoSomething的(ARG => FUNC(阿根廷,ARG1,ARG2),为arg0);
}


解决方案

编辑:正如评论指出这是部分应用程序,而不是钻营。我写我的不同的理解博客文章,该。人们可能会发现有趣的



好吧,这不是特别不同 - 但我从调用DoSomething的部分分离出钻营部分:

 公共静态Func键< TResult>应用< TResult,塔尔格> (Func键<塔尔格,TResult> FUNC,塔尔格ARG)
{
回报率()=> FUNC(ARG);
}

公共静态Func键< TResult>应用< TResult,TArg1,TArg2> (Func键< TArg1,TArg2,TResult> FUNC,
TArg1 ARG1,ARG2 TArg2)
{
回报率()=> FUNC(ARG1,ARG2);
}

//等



然后:

  DoSomething的(应用(富,1)); 



这样,你可以重用在其他情况下钻营码 - 包括在您不希望的情况下马上致电新返回委托。 (您可能需要更多的后来咖喱它,例如。)


Given a method DoSomething that takes a (parameterless) function and handles it in some way. Is there a better way to create the "overloads" for functions with parameters than the snippet below?

public static TResult DoSomething<TResult>(Func<TResult> func)
{
    //call func() and do something else
}

public static TResult DoSomething<T0, TResult>(
    Func<T0, TResult> func,
    T0 arg0)
{
    return DoSomething(() => func(arg0));
}

public static TResult DoSomething<T0, T1, TResult>(
    Func<T0, T1, TResult> func,
    T0 arg0, T1 arg1)
{
    return DoSomething(arg => func(arg, arg1), arg0);
}

public static TResult DoSomething<T0, T1, T2, TResult>(
    Func<T0, T1, T2, TResult> func,
    T0 arg0, T1 arg1, T2 arg2)
{
    return DoSomething(arg => func(arg, arg1, arg2), arg0);
}

解决方案

EDIT: As noted in comments, this is partial application rather than currying. I wrote a blog post on my understanding of the difference, which folks may find interesting.

Well, it's not particularly different - but I'd separate out the currying part from the "calling DoSomething" part:

public static Func<TResult> Apply<TResult, TArg> (Func<TArg, TResult> func, TArg arg)
{
    return () => func(arg);
}

public static Func<TResult> Apply<TResult, TArg1, TArg2> (Func<TArg1, TArg2, TResult> func,
                                                          TArg1 arg1, TArg2 arg2)
{
    return () => func(arg1, arg2);
}

// etc

Then:

DoSomething(Apply(foo, 1));

That way you can reuse the currying code in other situations - including cases where you don't want to call the newly-returned delegate immediately. (You might want to curry it more later on, for example.)

这篇关于正确的柯里在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆