I have a service that will handle an async socket. I will have several different request types that will be received by this service, but I want to avoid having any sort of switch statement to decide how to handle the received data.
Right now, I have a request object that will contain sender info, request type, and a generic object that will contain info that has to do with the request.
Ex: Login request will be sent with a Name/password hash.
The only way I can think to handle these once they've been reconstructed is to have a large switch statement that says
if (requestType = 0)
HandleLogin(receivedData);
else if (requestType = 1)
HandleDataRequest(receivedData);
I thought of abstraction but I would think since the classes need to be shared by the client/server in order to be serialized and deserialized, the client would have the server logic on it's class as well.
class LoginRequest : Request
{
public override void HandleRequest()
{
// Server logic here. But then client
// would have this useless logic in it's library.
}
}
If someone could point me in the right direction I would appreciate it!
If you are using C# 4.0+, and if your complete set of request types is known at compile time (which is sounds to be), you can use the dynamic keyword and method overloading to avoid using a switch statement.
First, create a version of the handle method for each type of request.
void HandleRequest(LoginRequest request)
{
}
void HandleRequest(DataRequest request)
{
}
Then, create a dynamically typed instance of your request data and use it to call your overloaded method.
dynamic request = receivedData;
HandleRequest(request);
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.