views:

3133

answers:

4

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 I need the parameters values in the string not the parameter types.

A: 

Ok, so this is what I've come up with - does anyone think its particularly inefficient?

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 += ")";
Ash
While the most important point is that I don't think this does what you think it does, yes it's inefficient - in various ways. Would you like to see a more efficient version which does the same thing, just for educational value?
Jon Skeet
(looped string concatenation vs StringBuilder, multiple calls to GetParameters(), etc).
Marc Gravell
+2  A: 

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...

Jon Skeet
Downvoters: explanations are helpful.
Jon Skeet
At my question http://stackoverflow.com/questions/2729580/how-to-get-the-parameter-names-of-an-objects-constructors-reflection people answer than you cannot get parameter names either -- maybe this is why you got downvoted.
Tom
With Reflection you can get parameter names: http://msdn.microsoft.com/en-us/library/system.reflection.parameterinfo.aspx
Nelson
+2  A: 

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.

Scott Muc
A: 

Unfortunately that's not gonna work..What you are gaining by using GetValue is just retrieving the item of the array - in effect the ParameterInfo object. There is no way to get the parameter value with this :(

Alexey