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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/471693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 04:43:13  来源:igfitidea点击:

Using reflection to get method name and parameters

c#.netmemcachedsystem.reflection

提问by Ash

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,

我正在尝试根据方法名称和参数以编程方式为Memcached创建密钥。所以如果我有一个方法,

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,但是如何获取字符串中的参数值,而不是参数类型?

采纳答案by Scott Muc

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.

你正在寻找的是一个拦截器。顾名思义,拦截器拦截方法调用并允许您在调用方法之前和之后执行操作。这在许多缓存和日志框架中非常流行。

回答by Ash

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

回答by Jon Skeet

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

您无法从反射中获取方法参数值。您必须使用调试/分析 API。您可以获取参数名称和类型,但不能获取参数本身。对不起...