In general, everything in your answer is possible, except for this line:
result = svcClient.serviceRefMethod;
Which is obviously a crucial call... In order to dynamically invoke a function on an object you can do a few things. An easy one is to change your function signature to:
public T CallServiceReference<T>(ServiceReference svcClient, method serviceRefMethod)
but then calling code needs to new up the ServiceReference
and pass in a reference to svcClient.[desiredFunction]
as the serviceRefMethod
.
An alternative is to change your signature to:
public T CallServiceReference<T>(string serviceRefMethodName)
and then use Reflection to find the method and invoke it. You will get no compile time validation (so if you have a typo it'll crash at runtime) but you'll get dynamic invokes. For example:
svcClient.GetType().InvokeMember(
methodName, /* what you want to call */
/*
Specifies what kinds of actions you are going to do and where / how
to look for the member that you are going to invoke
*/
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.InvokeMethod,
null, /* Binder that is used for binding */
svcClient, /* the object to call the method on */
null /* argument list */
);
Extra info based on your update (P.S. That probably could have been a separate question)
You now want to pass in not just a method but also the invocation of the method. Since not every method is invoked the same you are trying to do this at the call site, but that is before you actually want to invoke the method. Essentially what you're trying to do is shuttle around code that will only be executed later on (in the context of GetDataFromService
).
You can either go the reflection route (in which case you pass in an object[]
of parameters that you pass to the InvokeMember
call or you look into Func
which allows you to create some code that you run whenever you invoke the Func
. For example:
GetDataFromService(new Func<object>(() => { return client.DataCall(username); }));