Reputation: 29
I have this object that I'm serializing and sending to a server over TCP/IP and I need to deserialize it and fire it off in a message of the right type. I'm using .net 4.
The problem is that the object could be of several different types and the messenger needs to know the type of what it's sending. What I want to do is to send a string or Type object along that will specify what the main object's type is. Right now I'm doing this, but it only works for one type:
public void generic_Obj(Object obj)
{
//Entity is a class that I define elsewhere
//I'm using the Galasoft MVVM Light messenger
Messenger.Default.Send<Entity>((Entity)obj, "token");
}
I want to do something like this using reflection:
public void gen_Obj(Object obj, Type genType, string token)
{
//this doesn't work btw
Messenger.Default.Send<genType>((genType)obj, token);
}
I've tried all different methods of dynamic casting and such using reflection, some of them worked, but my real problem is finding something to put in between those <> brackets in the messenger call.
Upvotes: 2
Views: 384
Reputation: 31799
You can also do this in .net 4 using the dlr instead of reflection. The opensource framework Impromptu-interface has a helper method that makes it easy.
public void gen_Obj(Object obj, Type genType, string token)
{
Impromptu.InvokeMemberAction(Messenger.Default,"Send".WithGenericArgs(genType),obj,token)
}
Upvotes: 0
Reputation: 564323
If you generate a MethodInfo
for the Send
method using reflection, you can use MethodInfo.MakeGenericMethod to create the method with the specific type defined by genType
.
Once you've done that, MethodBase.Invoke can be used to call the method with your arguments.
Upvotes: 1