Get generic type in Async callback
I'm writing a library that communicates with a JsonRpc service via HTTP. All HTTP operations are done async by design.
Each command sent to the JsonRpc service will result in the server responding with a list of items.
The process is user calls GetXXXX method and provides a callba开发者_开发技巧ck (Very cut down version):
GetArtists(userCallback)
{
var state = new AsyncState<Artist>(userCallback);
jsonRpcClient.post(uri, internalCallback, AsyncState);
}
GetArtistsInternalCallback(httpStatusCode, responseBody, asyncState)
{
var realState = asyncState as AsyncState<Artist>.
// parse response body in to list of Artists
realState.UserCallback(List<Artist>);
}
UserCallback(List<Artist> artists)
{
User can do something with result
}
Now the Async state is generic, so if I had a method called GetAlbums for example the user would supply a callback with a signature of UserCallback(List albums) etc.
This is working fine but now what I want to do is make the InternalCallback generic. I have a lot of GetXXXX methods to implement and they all follow the exact same pattern.
I want my AsyncState to have a delegate on it that processes the server response so the InternalCallback would look something like:
InternalCallback(httpStatusCode, responseBody, asyncState)
{
var realState = asyncState as AsyncState<MAGICALLY-FIGURE-OUT-TYPE>.
*Do generic work here*
var listOfItems = asyncState.ProcessServerResponse(responseBody)
realState.UserCallback(List<MAGIC-TYPE> listOfItems);
}
So this would allow me to stop repeating the InternalCallback for every GetXXX method (Only thing that changes is the type).
But I now have the problem of how do I figure out the type of the state object in the callback? Up until now it's explicitly declared i.e. GetArtistsInternalCallback knows it's working with Artists but if I had a generic callback how would it figure out the type?
EDIT: Also if it makes any difference the Artist and Album types are derived from a common base class called MediaItem.
Cheers,
Tyler
It's hard to tell from the somewhat pseudo-code presented, but is there any reason you couldn't just make InternalCallback a generic method, and supply the type argument when you create the callback delegate instance?
The method can be generic even though the delegate isn't. Here's an example:
using System;
class Test
{
delegate void Callback(object o);
static void Main()
{
Callback callback = ShowType<int>;
callback(10);
}
static void ShowType<T>(object value)
{
Console.WriteLine("Value = " + value);
Console.WriteLine("typeof(T) = " + typeof(T));
Console.WriteLine("value.GetType() = " + value.GetType());
}
}
Of course, you have to specify the right type when you create the callback, but it sounds like this wouldn't be a problem in your situation.
精彩评论