使用反射获取方法名和参数
我正在尝试找到一种方法,根据方法名称以编程方式为 Memcached 创建密钥和参数。 因此,如果我有一个方法,
string GetName(int param1, int param2);
它将返回:
string key = "GetName(1,2)";
我知道您可以使用反射获取 MethodBase,但是如何获取字符串中的参数值,而不是参数类型?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法从反射获取方法参数值。 您必须使用调试/分析 API。 您可以获取参数名称和类型,但不能获取参数本身。 对不起...
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...
您正在寻找的是拦截器。 正如其名称所示,拦截器拦截方法调用,并允许您在调用方法之前和之后执行操作。 这在许多缓存和日志框架中非常流行。
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):