Conversion between Action and Func.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.