[英]Passing a method with parameter Func<T> and getting TResult
So basically T has a return type, I want to get back the generic return type. 所以基本上T具有返回类型,我想找回通用返回类型。 Example:
例:
private TResult EndInvoke<T, TResult>(Func<T, TResult> asyncCaller, IAsyncResult asyncResult)
{
TResult result = default(TResult);
try
{
result = asyncCaller.EndInvoke(asyncResult);
}
catch (Exception exception)
{
// get exception details.
}
return result;
}
How do I pass just the T calling the method and get the TResult? 如何仅传递T调用方法并获得TResult? Mind you, I only have the T.
请注意,我只有T。
EDIT: I meant how do I call this method? 编辑:我的意思是我怎么称呼这个方法?
EDIT: I want a generic EndInvoke, because I am a huge try catch on different EndInvokes, then I want the result from the EndInvoke. 编辑:我想要一个通用的EndInvoke,因为我在不同的EndInvokes上进行了大量尝试,然后我希望从EndInvoke获得结果。
I suggest converting your generic EndInvoke<,>
method to an extension method first. 我建议您首先将通用
EndInvoke<,>
方法转换为扩展方法。
public static class FuncExtensions
{
public static TResult EndInvoke<T, TResult>(this Func<T, TResult> asyncCaller, IAsyncResult asyncResult)
{
// ...
}
}
This will simplify the method call. 这将简化方法调用。 As an example, I'll call a method that calculates the square of an integer.
例如,我将调用一个计算整数平方的方法。
private int Square(int x)
{
return x * x;
}
In your client code, you'd call it like this: 在客户代码中,您可以这样称呼它:
Func<int, int> caller = new Func<int, int>(Square);
int x = 5;
int y = default(int);
caller.BeginInvoke(x,
asyncResult =>
{
y = caller.EndInvoke(asyncResult);
},
null);
Console.WriteLine("The square of {0} is {1}", x, y);
EDIT 编辑
This example has not been tested in any way, and contains an obvious race condition. 该示例未经任何测试,并且包含明显的竞争条件。
Not sure that I understand correctly, but I think that if you want the Func return value, you should drop the IAsyncResult. 不确定我是否正确理解,但是我认为,如果您想要Func返回值,则应该删除IAsyncResult。
Example: 例:
private TResult GetResult<T, TResult>(Func<T, TResult> asyncCaller, IAsyncResult asyncResult)
{
TResult result = default(TResult);
result = asyncCaller(argument...);
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.