简体   繁体   中英

How to get a method's parameter values from within the method using reflection?

I have hundreds of functions, each with different names and parameters. Every time a function is called, I need to log the method name, the parameter names and the values which the client passes in via the parameters. But I don't want to write the logging code for every function. It takes a long time, and every time a function's parameters are changed the logging code needs to change too.

So I hope I can write one block of code, and insert it into the beginning of every function. This block of code uses reflection to get the method name, names of the parameters, and most importantly, the values passed into the function via the parameters.

How do I do that?

Getting the method name is easy via [CallerMemberName] on a helper function like:

static string Me([CallerMemberName]string caller=null) => caller;

Getting the MethodInfo , and thus the ParameterInfo definitions (including the names) is pretty easy, but not very efficient. Getting the parameter values is not a thing you can do with the reflection API, and even if it could: the performance would be catastrophically bad. Since you say

and most importantly, the values passed into the function via the parameters.

I think you need to look at alternatives. One of which might just be "add the code you need manually". IL-weaving at build-time might be an option, but that's a much more advanced topic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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