简体   繁体   中英

Delegate method call which has params

I have a number of WCF calls which I would like to have a try catch around them. Instead of copying the same block of try catch , I would like to delegate the function call.

Here is my sample original function (cut down);

public DTO_Echo_Response SendEcho(DTO_Echo_Request request)
{
    try
    {
        return Proxy.SendEcho(request);
    }
    catch (System.ServiceModel.CommunicationException)
    {
        throw new Communication_Error("Communication Error");
    }
}

I would like something like the following:

public DTO_Echo_Response SendEcho(DTO_Echo_Request request)
{
    // invoke Process(Proxy.SendEcho(request));
}

public _DTO_BaseResponse Process(Func myFunction)
{
    try
    {
        return myFunction();
    }
    catch (System.ServiceModel.CommunicationException)
    {
        throw new Communication_Error("Communication Error");
    }
}

I have visited many articles and tried many different things which were way off the mark.

thank you

You're pretty close. Try this:

public DTO_Echo_Response SendEcho(DTO_Echo_Request request)
{
    return Process(() => Proxy.SendEcho(request));
}

public TResult Process<TResult>(Func<TResult> myFunction)
{
    try
    {
        return myFunction();
    }
    catch (System.ServiceModel.CommunicationException)
    {
        throw new Communication_Error("Communication Error");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM