Using reflection to get method name and parameters

天涯浪子 提交于 2019-12-17 09:54:19

问题


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?


回答1:


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.




回答2:


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




回答3:


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 += ")";


来源:https://stackoverflow.com/questions/471693/using-reflection-to-get-method-name-and-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!