代码之家  ›  专栏  ›  技术社区  ›  Snak3byte

将方法调用及其参数传递给其他方法

  •  0
  • Snak3byte  · 技术社区  · 16 年前

    我正在使用一个外部自动化库,其中包含一组参数为1或2的API,这些参数随机抛出TargetInvocationException。第二次或第三次调用这些API通常有效。因此,我创建了两个助手方法来封装多重重试逻辑

    //Original API calls
    bool result1 = Foo1(true);
    int result2 = Foo2(4, "abc");
    
    //New API calls
    bool result1 = SafeMethodCall(Foo1, true);
    int result2 = SafeMethodCall(Foo2, 4, "abc");
    
    
    //Helper Methods
    public static TResult SafeMethodCall<T, TResult>(
        Func<T, TResult> unSafeMethod,
        T parameter)
    {
        int numberOfMethodInvocationAttempts = 3;
        int sleepIntervalBetweenMethodInvocations = 10000;
    
        for (int i = 0; i < numberOfMethodInvocationAttempts; i++)
        {
            try
            {
                return unSafeMethod(parameter);
            }
            catch (System.Reflection.TargetInvocationException ex)
            {
                System.Threading.Thread.Sleep(sleepIntervalBetweenMethodInvocations);
            }
        }
    }
    
    public static TResult SafeTargetInvocationMethodCall<T1, T2, TResult>(
        Func<T1, T2, TResult> unSafeMethod,
        T1 parameter1,
        T2 parameter2)
    {
        int numberOfMethodInvocationAttempts = 3;
        int sleepIntervalBetweenMethodInvocations = 10000;
    
        for (int i = 0; i < numberOfMethodInvocationAttempts; i++)
        {
            try
            {
                return unSafeMethod(parameter1, parameter2);
            }
            catch (System.Reflection.TargetInvocationException ex)
            {
                System.Threading.Thread.Sleep(sleepIntervalBetweenMethodInvocations);
            }
        }
    }
    

    问题:如果您看到上面的两个助手方法具有相同的主体,唯一的区别是Try块内的unsafemethod调用。在这里我如何避免代码重复,因为我可能需要添加一个接受

    Func<TResult>
    

    作为另一个参数类型。

    1 回复  |  直到 16 年前
        1
  •  1
  •   Jon Skeet    16 年前

    只是通过 Func<TResult> 这样称呼它:

    bool result1 = SafeMethodCall(() => Foo1(true));
    int result2 = SafeMethodCall(() => Foo2(4, "abc"));
    

    换句话说,在委托本身中封装参数。