Func<TResult> 和 Func<T, TResult> 可以在方法签名中有 1 个名称吗?
Could Func<TResult> and Func<T, TResult> have 1 name in method signature?
我有两种方法:
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 个方法?
就像是
"private static async Task GetInfoAsync(MyClient service, Something??, string resultText, string param)"
不,但一般来说,您可以执行部分函数(参见示例 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
。
我有两种方法:
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 个方法? 就像是 "private static async Task GetInfoAsync(MyClient service, Something??, string resultText, string param)"
不,但一般来说,您可以执行部分函数(参见示例 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
。