Why?
Assume that you have a WebService Proxy. You can use the following methods:
public class Proxy : IProxy{ public void Foo(int i, bool b) { // do something. } public string Bar(string str) { return "Something"; }}
You can call:
Proxy p = new Proxy(); p.Foo(0, true); string s = p.Bar("hello");
However, you need to handle a series of exceptions, such:
string CallBar(string str){ try { return proxy.Bar(str); } catch (EndpointNotFoundException ee) { // handle it. } catch (TimeoutException te) { // handle it. } catch (CommunicationException ce) { // handle it. } catch (Exception e) { // handle it. } return null;}
If the Proxy method needs to be called in many places, do you want to repeat this large piece of code? Of course not. So we encapsulate it:
public T CallProxy<T>(Func<Proxy, T> func){ try { return func(proxy); } catch { // skip all exception handling code. } return default(T);}
In this way, we call proxy. Bar ("hello "):
string str = CallProxy(proxy => proxy.Bar("Hello"));
How to deal with Foo? Another CallProxy needs to be defined:
public void CallProxy(Action<Proxy> action) { // do something here: }
I don't want to write repeated code. If a conversion function converts an Action to Func:
public static class Extension{ public static Func<T, object> ToFunc<T>(this Action<T> action) { return t => { action(t); return null; }; } }
The preceding CallProxy can be simply implemented as follows:
public void CallProxy(Action<Proxy> action){ CallProxy(action.ToFunc());}
CallProxy(proxy => proxy.Foo(0, true));
In fact, there are many ways to simplify it.