0

所以基本上 T 有一个返回类型,我想取回通用返回类型。例子:

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;
}

如何只传递调用该​​方法的 T 并获取 TResult?请注意,我只有T。

编辑:我的意思是如何调用此方法?

编辑:我想要一个通用的 EndInvoke,因为我对不同的 EndInvoke 有很大的尝试,然后我想要 EndInvoke 的结果。

4

2 回答 2

1

我建议先将您的通用EndInvoke<,>方法转换为扩展方法。

public static class FuncExtensions
{
    public static TResult EndInvoke<T, TResult>(this Func<T, TResult> asyncCaller, IAsyncResult asyncResult)
    {
        // ...
    }
}

这将简化方法调用。例如,我将调用一个计算整数平方的方法。

private int Square(int x)
{
    return x * x;
}

在您的客户端代码中,您可以这样称呼它:

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);

编辑

这个例子没有经过任何测试,并且包含一个明显的竞争条件。

于 2014-02-17T08:23:55.090 回答
0

不确定我的理解是否正确,但我认为如果你想要 Func 返回值,你应该删除 IAsyncResult。

例子:

private TResult GetResult<T, TResult>(Func<T, TResult> asyncCaller, IAsyncResult asyncResult)
    {
        TResult result = default(TResult);
        result = asyncCaller(argument...);

        return result;
    }
于 2014-02-17T07:33:24.607 回答