将方法包装到func中

时间:2017-12-07 13:36:33

标签: c# generics delegates func polly

我想在Polly框架周围创建一个通用包装器,以便可以实现单一实现。为了实现它,我写了下面的代码

    private Policy GetPolicy(EType eType)
    {
        var policy = default(Polly.Policy);

        switch (eType)
        {                

            case EType.T:
                policy = Policy.Handle<SomeException>().Retry(n, x => new TimeSpan(0, 0, x));
                break;                
        }
        return policy;
    }  

我在我的一个包装方法

中使用了上述方法
   public TOutput Execute<TOutput>(Func<TOutput> func, EType eType)
    {
        var policy = GetPolicy(eType);

        return policy.Execute(() => func());
    }

现在为了消费它,我写了一个示例方法

       var handleError = new HandleError();
        var connection = handleError.Execute(() => factory.CreateConnection(), ExceptionType.Transient);

直到上面一切正常,但是一旦我在一个接受参数的方法中开始调用它,那么它会抛出错误

     var handleError = new HandleError();
        handleError.Execute(() => channel.ExchangeDeclare(queueDetail.ExchangeName, ExchangeType.Fanout), ExceptionType.Transient);

     The type arguments for method 'HandleError.Execute<TOutput>(Func<TOutput>, ExceptionType)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

1 个答案:

答案 0 :(得分:2)

您需要两个Execute重载,一个用于返回值的函数,另一个用于那些不返回值的函数:

public TOutput Execute<TOutput>(Func<TOutput> func, ExceptionType exceptionType)
{
    var policy = GetPolicyFromExceptionType(exceptionType);
    return policy.Execute(func);
}

public void Execute(Action action, ExceptionType exceptionType)
{
    var policy = GetPolicyFromExceptionType(exceptionType);
    policy.Execute(action);
}

然后你可以传递任何东西,包括带参数的函数:

// calls first overload
Execute(() => ImReturningValue(parameter1));
// calls second
Execute(() => IDoNot(parameter1));

Policy.Execute方法也有相同的重载(一个用于Func,一个用于Action) - 所以你可以毫无问题地将任何一个传递给它。

相关问题