Func <tresult>和Func <t,tresult =“”>在方法签名中有1个名字吗?</t,> </tresult>

时间:2015-03-27 09:06:58

标签: c#-4.0 func

我有两种方法:

private static async Task<T> GetInfoAsync<T>(MyClient service, Func<Task<T>> funcAsync, string resultText)
    {
        var result = default(T);

        if (service != null) {
            try {
                service.Open();
                result = await funcAsync();
                service.Close();
                Console.WriteLine(resultText);
            } catch (Exception ex) {
                service.Abort();
            }
        }
        return result;
    }

    private static async Task<T> GetInfoAsync<T>(MyClient service, Func<string,Task<T>> funcAsync, string resultText, string param)
    {
        var result=default(T);

        if (service != null) {
            try {
                service.Open();
                result = await funcAsync(param);
                service.Close();
                Console.WriteLine(resultText);
            } catch (Exception ex) {
                service.Abort();
            }
        }
        return result;
    }

是否可以为2个功能创建1个方法? 就像是 &#34;私有静态异步任务GetInfoAsync(MyClient服务,Something ??,字符串resultText,字符串参数)&#34;

1 个答案:

答案 0 :(得分:1)

不,但一般情况下你可以做一个部分函数(参见例如http://blogs.msdn.com/b/wesdyer/archive/2007/01/29/currying-and-partial-function-application.aspx),给定带参数的函数,用该参数的固定值调用它。

// The original function
Func<string, Task<T>> fullFunction = x => ...;

// The partial function
string param = "...";
Func<Task<T>> partialFunction = () => fullFunction(param);

因此GetInfoAsync的来电者需要创建此partialFunction并将其传递给GetInfoAsync