2

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.

user686661
  • 29
  • 1
  • possible duplicate of [How to use reflection to call generic Method?](http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method) – nawfal Jan 18 '14 at 05:47

2 Answers2

1

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.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Thanks for the help. I was able to make this work, but it wasn't easy. Anybody else who wants to do similar should have a look at [GetMethod for generic method](http://stackoverflow.com/questions/4035719/getmethod-for-generic-method) – user686661 Apr 01 '11 at 21:31
0

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)
}
jbtule
  • 31,383
  • 12
  • 95
  • 128