使用委托来集中样板代码的通用函数?

时间:2013-03-01 01:11:10

标签: c# generics delegates

我正在编写一个类似于WCF接口代理的类,但它有一些专门但是样板的额外代码。我想提取样板代码并使用通用或其他机制来包装对类的内部实例的调用。

public interface IMyInterface
{
  long fn1(int param1, int param2);
}

public class MyInterfaceProxy : IMyInterface
{
  // generated code
}

public class MyClass : IMyInterface
{
  private MyInterfaceProxy _myProxy; // implements IMyInterface
  public long fn1(int param1, int param2)
  {
    long result = null;
    CallMethod(
               delegate(IMyInterface svc)
               {
                   result = svc.fn1(param1, param2);
               });
    return result;
  }

  private T CallMethod( ??? )
     where T : class
  {
    T result = null;

    // some boilerplate code
    // Call the delegate, passing _myProxy as the IMyInterface to act on
    // some more boilerplate code

    return result;
  }

}

如果有帮助,样板代码可以表示重试逻辑,超时行为,标准化异常处理行为等。

所以这是我的问题:

  1. 是否有标准或首选方法来解决此问题?
  2. 如果泛型是首选机制,CallMethod函数的签名是什么?

1 个答案:

答案 0 :(得分:2)

我认为这就是你要找的东西。组成函数还有很多工作要做。这是函数式编程范式的表面划痕,我们现在可以在c#中使用它的一些非常好。

编辑:添加了匿名函数实现,以更好地模拟您的委托方案。

class Program
{
    static void Main(string[] args)
    {
        string resFromFunctionToBeWRapped = CallMethod(() => FunctionToBeWrapped());

        int resFromAnon = CallMethod(() => {
            Console.WriteLine("in anonymous function");
            return 5;
        } );

        Console.WriteLine("value is {0}", resFromFunctionToBeWRapped);
        Console.WriteLine("value from anon is {0}", resFromAnon);

        Console.ReadLine();
    }

    private static TResult CallMethod<TResult>(Func<TResult> functionToCall) //where T : class
      {
        Console.WriteLine ("in wrapper");

        var ret = functionToCall();

        Console.WriteLine("leaving wrapper");

        return ret;
      }

    private static string FunctionToBeWrapped()
    {
        Console.WriteLine("in func");
        return "done";
    }

}