Action and Func<object> 之间的转换.

it2022-05-08  10

为什么需要这个?

假设你有一个WebService 的Proxy, 有方法:

public class Proxy : IProxy { public void Foo(int i, bool b) { // do something. } public string Bar(string str) { return "Something"; } }

你可以这样调用:

Proxy p = new Proxy(); p.Foo(0, true); string s = p.Bar("hello");

 

但是你需要处理一系列的Exception, 例如:

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; } 如果有很多地方需要调用这个Proxy 的方法,你希望重复这一大段代码吗?当然不希望。于是我们对它进行封装: public T CallProxy<T>(Func<Proxy, T> func) { try { return func(proxy); } catch { // skip all exception handling code. } return default(T); }  

这样,我们调用 proxy.Bar(“hello”):

string str = CallProxy(proxy => proxy.Bar("Hello"));  

对Foo 怎么处理? 需要定义另一个CallProxy:

public void CallProxy(Action<Proxy> action) { // do something here: }

我不想写重复代码,如果有一个转换函数把Action 转化成Func:

public static class Extension { public static Func<T, object> ToFunc<T>(this Action<T> action) { return t => { action(t); return null; }; } }

上面的CallProxy 就可以简单的实现为:

public void CallProxy(Action<Proxy> action) { CallProxy(action.ToFunc()); }

CallProxy(proxy => proxy.Foo(0, true));

其实还有很多的地方可以通过这种方式来简化。

转载于:https://www.cnblogs.com/oujinliang/archive/2009/11/30/1613985.html


最新回复(0)