通用方法调用代码

时间:2011-11-09 14:20:34

标签: c# generics delegates

我有一个带有不同签名的方法的接口(这里的上下文是一个WCF回调接口)。我的服务器有一个客户列表。为了响应事件,我想在每个客户端上调用接口的方法。这个调用周围有一堆样板代码(检查客户端是否存活,如果此客户端包含在列表中进行回调,请尝试catch,如果操作失败则删除客户端等)。什么是将此锅炉板代码提取到通用CallBackClients(SomeKindOfGenericDeligate method_to_call)的最佳方法,其中method_to_call是接口方法之一。

ICallback {
    void Fish(string my_string);
    void SuperFish(int my_int, double my_double);
    ... etc ...
}

CallBackClients( -- ?? generic delegate ?? -- ) {
    foreach (IClientCallback client in client_list) {
        // The boiler plate code:
        if (((ICommunicationObject)client.callback).State == CommunicationState.Opened) {
            try {
               Do method call based on delagate / lamda code passed in - how ??
            }
            catch (Exception e) {
                Remove_client(client, method.ToString(), e);
            }
        }
        else
            Remove_client(client, method.ToString());
        }
    }
}

来电者的伪代码:

void EventHandler_A() {
    // Call Fish method on all clients:
    CallBackClients(Fish("hello"));
}

void EventHandler_B() {
    // Call SuperFish method on all clients:
    CallBackClients(SuperFish(10, 5.3);
}

1 个答案:

答案 0 :(得分:2)

您可以封装一个方法,以便稍后在IClientCallBack中的任何给定Action<IClientCallBack>调用:

CallBackClients(Action<IClientCallBack> actionOnDelegates) {
    foreach (IClientCallback client in client_list) {
        // The boiler plate code:
        if (((ICommunicationObject)client.callback).State == CommunicationState.Opened) {
            try {
               actionOnDelegates(client);
            }
            catch (Exception e) {
                Remove_client(client, method.ToString(), e);
            }
        }
        else
            Remove_client(client, method.ToString());
        }
    }
}

然后会这样调用;这些创建了一个匿名方法来调用指定的client上的方法:

void EventHandler_A() {
    // Call Fish method on all clients:
    CallBackClients(client => client.Fish("hello"));
}

void EventHandler_B() {
    // Call SuperFish method on all clients:
    CallBackClients(client => client.SuperFish(10, 5.3);
}