简体   繁体   English

使用反射获取方法名称和参数

[英]Using reflection to get method name and parameters

I am trying to workout a way to programatically create a key for Memcached , based on the method name and parameters. 我正在尝试以一种方式编写一种方法,以编程方式为Memcached创建一个基于方法名称和参数的密钥。 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? 我知道您可以使用反射获取MethodBase,但是如何获取字符串中的参数值,而不是参数类型?

You can't get method parameter values from reflection. 您无法从反射中获取方法参数值。 You'd have to use the debugging/profiling API. 您必须使用调试/分析API。 You can get the parameter names and types, but not the parameters themselves. 您可以获取参数名称和类型,但不能获取参数本身。 Sorry... 抱歉...

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. 这在许多缓存和日志记录框架中非常流行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM