委托签名/泛型委托? [英] Delegate signature/generic delegate?

查看:191
本文介绍了委托签名/泛型委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Windows Mobile设备来调用Web服务的一个项目。

I'm working on a project that uses a Windows Mobile device to call a web service.

有一个要求,即规定,如果一个服务调用失败,那么用户应该被提示重试。目前,有它要求所有的Web服务代理的方法的代理服务,以及在调用失败有一些code,提示重试用户,然后再改掉呼叫。它看起来是这样的:

There's a requirement that states that if a service call fails then the user should be prompted to retry. Currently, there's a service agent which calls all the methods on the web service proxy, and if the call fails there's some code which prompts the user to retry, and then trys the call again. It looks something like this:

public void MyServiceCall(string stringArg, bool boolArg, int intArg)
{
    try
    {
        MyWebService.MyServiceCall(stringArg, boolArg, intArg);
    }
    catch(SoapException ex)
    {
        bool retry = //a load of horrid code to prompt the user to retry
        if (retry)
        {
            this.MyServiceCall(stringArg, boolArg, intArg);
        }
    }
}

在追赶的东西看起来在系统上有很多混乱比那个片段,以及CTRL-C CTRL-V模式已被用于复制其在每一个服务调用。我想重构这个重复code到一个方法,但我不能确定的重试方法调用的最好方法。我想有一个委托作为参数传递给我的新方法,但因为我不知道签名,我不确定如何做到这一点的通用方法。任何人都可以帮忙吗?谢谢你。

The stuff in the catch looks a lot messier on the system than in that snippet, and the CTRL-C CTRL-V pattern has been used to replicate it in every service call. I'd like to refactor this duplicated code into a method but I'm unsure of the best way to retry the method call. I was thinking of having a delegate as an argument to my new method, but since I won't know the signature I'm unsure of how to do this in a generic way. Can anyone help? Thanks.

推荐答案

我觉得你只需要两个方法:

I think you just need two methods:

protected void Invoke(Action action) {
    try {
       action();
    } catch {...} // your long boilerplate code
}
protected T Invoke<T>(Func<T> func) {
    try {
       return func();
    } catch {...} // your long boilerplate code
}

然后你可以使用:

Then you can use:

public void MyServiceCall(string stringArg, bool boolArg, int intArg)
{
    Invoke(() => MyWebService.MyServiceCall(stringArg, boolArg, intArg));
}

和同样也使用另一个版本与一个返回值的方法。如果需要,您还可以使代表们的服务本身作为一个参数 - 这可能是方便的的IDisposable 原因:

and likewise use the other version for methods with a return value. If you need to, you can also make the delegates take the service itself as an argument - which might be handy for IDisposable reasons:

protected void Invoke(Action<MyService> action) {
   using(MyService svc = new MyService()) {
     try {
       action(svc);
     } catch {...} // your long boilerplate code
   }
}
...
public void MyServiceCall(string stringArg, bool boolArg, int intArg)
{
    Invoke(svc => svc.MyServiceCall(stringArg, boolArg, intArg));
}

这篇关于委托签名/泛型委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆