C# 使用反射获取参数的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1867482/
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-06 21:29:43  来源:igfitidea点击:

C# Getting value of parms using reflection

c#reflection

提问by NealWalters

How can I get the values of parms (in a loop using reflection). In previous question, someone showed me how to loop through the parms using reflection.

如何获取 parms 的值(在使用反射的循环中)。在上一个问题中,有人向我展示了如何使用反射循环遍历参数。

static void Main(string[] args)
{
    ManyParms("a","b","c",10,20,true,"end");
    Console.ReadLine(); 
}

static void ManyParms(string a, string b, string c, int d, short e, bool f, string g)
{
    var parameters = MethodBase.GetCurrentMethod().GetParameters();
    foreach (ParameterInfo parameter in parameters)
    {
        string parmName = parameter.Name;
        Console.WriteLine(parmName); 
        //Following idea required an object first 
        //Type t = this.GetType();
        //t.GetField(parmName).GetValue(theObject));

    }
}

If you must know why I want to do this, please see here: .NET Reflection of all method parameters

如果你一定知道我为什么要这样做,请看这里: .NET Reflection of all method parameters



Thanks all - it seems like in Python, PERL, PHP this would be easy.
Even though it may not be reflection, if I use reflection to get the field name, seems like there would be an easy dynamic way to get the value based on the name. I haven't tried AOP (Aspect Oriented Programming) the solutions yet. This is one of those things that if I can't do it in an hour or two, I probably won't do it.

谢谢大家 - 似乎在 Python、PERL、PHP 中这很容易。
即使它可能不是反射,如果我使用反射来获取字段名称,似乎会有一种简单的动态方法来获取基于名称的值。我还没有尝试过 AOP(面向方面​​编程)的解决方案。这是如果我不能在一两个小时内完成的事情之一,我可能不会做。

采纳答案by LukeH

You can hack your way around this by creating an anonymous type inside your method and taking advantage of projection initialisers. You can then interrogate the anonymous type's properties using reflection. For example:

你可以通过在你的方法中创建一个匿名类型并利用投影初始化器来解决这个问题。然后您可以使用反射查询匿名类型的属性。例如:

static void ManyParms(
    string a, string b, string c, int d, short e, bool f, string g)
{
    var hack = new { a, b, c, d, e, f, g };

    foreach (PropertyInfo pi in hack.GetType().GetProperties())
    {
        Console.WriteLine("{0}: {1}", pi.Name, pi.GetValue(hack, null));
    }
}

回答by Jon Skeet

You can't, basically - at least not without hooking into the debugger/profiling API.

你不能,基本上 - 至少在没有挂钩调试器/分析 API 的情况下不能

In theory there couldbe some way of the StackFrameclass exposing parameter values, but it doesn't - and I suspect that in order to do so, you'd have to remove several optimisations.

从理论上讲,类可能会以某种方式StackFrame公开参数值,但事实并非如此 - 我怀疑为了这样做,您必须删除一些优化。

回答by Lucero

You can't via reflection, and you shouldn't do it anyways.

你不能通过反射,你也不应该这样做。

If you need this kind of functionality, use a proxy, e.g. via a RealProxy implementation which intercepts the call for you. Then, you can check and modify any parameter before the actual call is made (or even not do the original call at all, that's up to you).

如果您需要这种功能,请使用代理,例如通过 RealProxy 实现来拦截您的调用。然后,您可以在进行实际调用之前检查和修改任何参数(甚至根本不进行原始调用,这取决于您)。

回答by RaYell

You cannot do that. Reflection works on meta-data embedded during compilation and at that time parameter values are not known.

你不能这样做。反射适用于编译期间嵌入的元数据,当时参数值未知。

回答by Lasse V. Karlsen

Have you considered using AOP, like PostSharp?

你有没有考虑过使用 AOP,比如PostSharp

It can get access to argument values before your method executes, and your code would thus be reduced to a reusable attribute class, and an attribute applied to the methods that needs to have this check.

它可以在您的方法执行之前访问参数值,因此您的代码将被简化为可重用的属性类,并将属性应用于需要进行此检查的方法。

回答by Dror Helper

You cannot get the value of the method's parameters using reflection. Because reflection returns the metadata information. If you'd like to get the value of a specific field or property you need to use an instance as well (like you already know).

您无法使用反射获取方法参数的值。因为反射返回元数据信息。如果您想获取特定字段或属性的值,您还需要使用实例(就像您已经知道的那样)。

There are several ways to get a parameter's value using the inner plumbing of the .NET framework - namely profiler API and debugger API.

有几种方法可以使用 .NET 框架的内部管道获取参数的值 - 即分析器 API 和调试器 API。

You can use AOP for what you're trying to do, there is a Codeplex project called CThruthat might help you - using CThru you can intercept the method when it's being called and get the parameters it was called with.

您可以将 AOP 用于您想要做的事情,有一个名为CThru的 Codeplex 项目可能会对您有所帮助 - 使用 CThru 您可以在调用方法时拦截该方法并获取调用它的参数。

回答by Michael Freidgeim

PostSharp Diagnostics Toolkitsupports IncludeParameterValue option.

PostSharp 诊断工具包支持 IncludeParameterValue 选项。

If you want more details up to creating mini dump,

如果您想了解更多详细信息以创建小型转储,

see Accessing stack traces with MDbgEngine and PADREand Creating a custom PostSharp aspect (with IL transformation)

请参阅使用 MDbgEngine 和 PADRE 访问堆栈跟踪创建自定义 PostSharp 方面(使用 IL 转换)