如何获取调用方法的参数值? [英] How can I get the values of the parameters of a calling method?

查看:16
本文介绍了如何获取调用方法的参数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些代码,需要能够从调用类的方法中获取参数的.我知道如何获得 ParameterInfo[] 数组,但我不知道如何获得这些值.这甚至可能吗?

I'm writing some code that needs to be able to get the values of the parameters from the method that called into the class. I know how to get all the way to the ParameterInfo[] array, but I don't know how to then get the values. Is this even possible?

如果是的话,我认为这与使用 MethodInfo 对象中的 MethodBody 属性有关,该属性允许您检查 IL 流,包括属性,但我不知道该怎么做,而且我还没有在 Google 上找不到适用的代码.

If it is, I think it has something to do with using the MethodBody property from the MethodInfo object, which allows you to inspect the IL stream, including properties, but I don't know how to do it, and I haven't found applicable code on Google.

// Finds calling method from class that called into this one
public class SomeClass
{
    public static void FindMethod()
    {
        for (int i = 1; i < frameCount; i++)
        {
            var frame = new StackFrame(i);
            var methodInfo = frame.GetMethod();
            if (methodInfo.DeclaringType != this.GetType())
            {
                string methodName = frame.GetMethod().Name;
                var paramInfos = methodInfo.GetParameters();

                // Now what?? How do I get the values from the paramInfos

                break;
            }
            else if (i == frameCount - 1)
            {
                throw new TransportException("Couldn't find method name");
            }
        }
    }
}

推荐答案

你不能不自己反省堆栈(这很脆弱,因为许多优化可能意味着堆栈框架不是你所期望的,甚至参数传递的实际上并不是方法签名所暗示的(优化 JIT 编译器完全有可能发现您仅使用对象/结构的子字段并传递它).

You cannot do it without introspecting the stack yourself (and this is fragile since many optimizations may mean the stack frame is not what you expect, or even that the parameter passed is not in fact what the method signature would suggest (it is perfectly possible for an optimizing JIT compiler to spot that you are only using a sub field of an object/struct and pass that instead).

ParameterInfo 只是告诉您编译时方法的签名,而不是传递的值.

The ParameterInfo simply tells you the signature of the method as compiled, not the values that were passed.

自动实现这一目标的唯一现实方法是通过代码注入(通过 AOP 之类的东西)来创建数据并根据分析 IL 使用它做您想做的事情.

The only realistic way to achieve this automatically is via code injection (via something like AOP) to create the data and do what you want with it based on analysing the IL.

这通常不是一个好主意,如果您需要调试某些内容,请使用调试器,如果您需要记录某些内容,请明确说明您正在记录的内容.

This is generally not a good idea, if you need to debug something use a debugger, if you need to log something be explicit about what you are logging.

要清楚,简单的反射技术不能完全通用地实现您的愿望

To be clear simple reflective techniques cannot achieve what you desire with full generality

这篇关于如何获取调用方法的参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆