I hope i'm missing something obvious, but I'm having some troubles defining a method that takes a parameter of a method to fetch the method information for the passed method. I do NOT want actually execute the method.
I want to be able to do:
busObject.SetResolverMethod<ISomeInterface>(x=>x.GetNameById);
Where GetNameById is a method defined on the interface ISomeInterface. In this case, an example of the method being passed in's signature would be:
MyVarA GetNameById(int id){ .... }
In the above example, the SetResolverMethod's body should be able to return / store the string "GetNameById".
There is no standard signature the method being passed in will conform to (except that it will always return an object of some kind).
Currently I'm setting the method as a string (i.e. "GetNameById"), but I want it to be compile time checked, hence this question.
It's not particularly pretty/fluent but if you really want to avoid having to pass dummy parameter values then you can use an expression that returns a delegate.
The
SetResolverMethod
implementation would look something like this:Edit: If you're willing to create as set of overloads for each
Func<>
delegate, you can improve the fluency by including the method parameter types in the generic parameter types of your method.As you can see, the caller no longer needs to specify a delegate type, thus saving around 8 characters.
I've implemented three overloads for 0, 1 and 2 parameters:
There is no way to pass just the method itself. You could do it by wrapping the method in a delegate, but for that, you have to either have the
SetResolverMethod
method define the type of that delegate (which you can't do, because, as you said, there is no one signature), or explicitly specify that type when calling, which would be dirty.What you could do instead is have the
SetResolverMethod
take a lambda expression that takesISomeInterface
and returns whatever, and pass the actual execution of the method with whatever arguments as the body of that expression. Like so:The
SetResolverMethod
method will not actually execute the expression, only analyze it - therefore, your method will not actually be executed.Is this what you need?