我想围绕 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.
最佳答案
您需要两个 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) - 因此将任一重载传递给它都不会出现问题。
关于c# - 将方法包装到函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47696368/