C# 将方法包装到func中

C# 将方法包装到func中,c#,generics,delegates,func,polly,C#,Generics,Delegates,Func,Polly,我想围绕Polly框架创建一个通用包装器,这样就可以有单个实现。为了实现它,我写了下面的代码 private Policy GetPolicy(EType eType) { var policy = default(Polly.Policy); switch (eType) { case EType.T: policy = Policy.Ha

我想围绕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;
    }  
最重要的是,一切都很好,但只要我开始在一个使用参数的方法中调用相同的函数,它就会抛出错误

     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.
var handleError=new handleError();
handleError.Execute(()=>channel.ExchangeClare(queueDetail.ExchangeName,ExchangeType.Fanout),ExceptionType.Transient);
无法根据用法推断方法“HandleError.Execute(Func,ExceptionType)”的类型参数。尝试显式指定类型参数。

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

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

Policy.Execute
方法也有相同的重载(一个用于Func,一个用于Action)-因此您将不会有任何问题将任何一个重载传递给它。

“我已经尝试了下面的方法,但invain”这是什么意思?有错误吗?意外行为?你期望什么?你得到了什么?无论如何,我看不出你的包装纸有什么用处。通过委托提供一个方法,然后在
Execute
-method中直接调用该委托,这样做没有任何好处。您想在这里做什么?我闻到一个X-Y问题。@HimBromBeere-在问题中添加了错误没有足够的信息给出有意义的答案。告诉我们你想做什么,并解释为什么你不能做。例如,我看不到
Save
Execute
@Fildor之间的联系-添加在问题的底部,非常感谢您的帮助!!
     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.
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));