I am trying to rewrite some code that is part of a huge codebase. The code uses lambda expressions to pass objects to a common "Handler" that I am trying to rewrite. Here is a typical sample of code that I am given.
public class MyMessage : MyBaseClass
{
public int ValueA {get;set;}
public int ValueB {get;set;}
}
public class MyOtherMessage : MyBaseClass
{
public int ValueC {get;set;}
public int ValueD {get;set;}
}
public class Sender
{
Handler handler = new Handler();
handler.Send<MyMessage>(m => { m.ValueA=10; m.ValueB=20; });
}
Notice the Send-invocation with a lambda expression as input. The codebase has similar invocations 1000 of times. I would like to keep this code as it is. This code above used to call a Send-implementation in an old library that I am replacing with a new implementation of the Send-method. So I know that the invocation above work somehow.
I want to write a new Send method implementation that works with the Send invocation above.
In other words, I want to write the code of the Handler which shall receive the MyMessage object or the MyOtherMessage object. I know they are all subclasses of the common MyBaseClass.
I have tried it like this:
public class Handler
{
public void Send<T>(Action<T> actionmessage)
{
// actionmessage is an object of type Action<T>,
// I want to get the object of type T that was passed into the method.
}
}
The problem is that the object that is created with the lambda expression in the invocation is not easily retrieved. With my attempt here I get an action not an object. How do I get the object itself? I have also tried:
public class Handler
{
public void Send<T>(T message)
{
// This will not compile. I get:
// Cannot convert lambda expression
// to type 'object' because it is not a delegate type
}
}
Maybe I need to use reflection somehow?
Aucun commentaire:
Enregistrer un commentaire