Question

I am trying to workout a way to programatically create a key for Memcached, based on the method name and parameters. So if I have a method,

string GetName(int param1, int param2);

it would return:

string key = "GetName(1,2)";

I know you can get the MethodBase using reflection, but how do I get the parameters values in the string, not the parameter types?

Was it helpful?

Solution

What you're looking for is an interceptor. Like the name says, an interceptor intercepts a method invocation and allows you to perform things before and after a method is called. This is quite popular in many caching and logging frameworks.

OTHER TIPS

You can't get method parameter values from reflection. You'd have to use the debugging/profiling API. You can get the parameter names and types, but not the parameters themselves. Sorry...

This is what I've come up with (however, it may not be particularly efficient):

MethodBase method = MethodBase.GetCurrentMethod();
string key = method.Name + "(";
for (int i = 0; i < method.GetParameters().Length; i++) {
  key += method.GetParameters().GetValue(i);
  if (i < method.GetParameters().Length - 1)
    key += ",";
}
key += ")";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top