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

发布于 2024-07-13 04:21:14 字数 335 浏览 5 评论 0原文

我正在尝试找到一种方法,根据方法名称以编程方式为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

别念他 2024-07-20 04:21:14

您无法从反射获取方法参数值。 您必须使用调试/分析 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...

桃气十足 2024-07-20 04:21:14

您正在寻找的是拦截器。 正如其名称所示,拦截器拦截方法调用,并允许您在调用方法之前和之后执行操作。 这在许多缓存和日志框架中非常流行。

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.

最笨的告白 2024-07-20 04:21:14

这是我想出的(但是,它可能不是特别有效):

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

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 += ")";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文