I'm trying to make a class to handle invoking methods on a remote server using my own means. To make it easier on the client caller, I'm writing a generic class that accepts an interface so that the compiler will know the number of arguments and the return type of the method.
public class Service<TInterface&g开发者_Go百科t;
{
public TResult Invoke<TResult>(Func<TInterface, TResult> function)
{
// Do the work
}
}
So the idea is they could reference an assembly that has the interfaces, for example:
public interface ICalculator
{
int Add(int num1, int num2);
}
And then they could write code to hit the service like this:
var addend = new Service<ICalculator>(/* constructor */).Invoke(s => s.Add(3, 4));
The problem is that in the first code block, I need to know how to find out what arguments they passed in their lamda expression. How do I do that?
The easiest way to do that is to take an Expression<Func<TInterface,TResult>
instead; this is then trivial to pull apart. In fact, you can just lift my code from here which covers most scenarios. In particular, look at ResolveMethod
. Some discussion/explanation for this is here.
精彩评论