使用反射来获取参数的名称

发布于 2024-10-08 04:47:50 字数 395 浏览 0 评论 0原文

我有 ac# .net 2.0CF 应用程序,我不仅想获取传递给函数的参数的类型和值,还想获取变量名称。

例如:

void Show<PARAM>(PARAM p)
{
    Debug.WriteLine(string.Format("{0} {1} = {2}", typeof(PARAM).ToString, ???, p.ToString() );
}

bool foo = true;
Show(foo);

将输出“bool foo = true”;

在 C++ 中,我可以使用 ## 预处理器宏来完成此操作。

如果这在2.0中无法完成,那么在3.5或4.0中可以完成吗?

谢谢, 保罗·H

I have a c# .net 2.0CF application where I would like to get not only the type and value of a parameter passed to the function, but also the variable name.

For example:

void Show<PARAM>(PARAM p)
{
    Debug.WriteLine(string.Format("{0} {1} = {2}", typeof(PARAM).ToString, ???, p.ToString() );
}

bool foo = true;
Show(foo);

would output "bool foo = true";

In C++, I can do this with the ## pre-processor macro.

If this can't be done in 2.0, can it be done in 3.5 or 4.0?

Thanks,
PaulH

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

捂风挽笑 2024-10-15 04:47:50

如果我没记错的话,反射是不可能的,因为变量名不在程序集中,而 p 是变量名。

If I remember correctly, this is not possible with reflection as variable names are not in the assemblies, and p is a variable name.

山有枢 2024-10-15 04:47:50
using System.Reflection;


ParameterInfo[] info = MethodInfo.GetCurrentMethod().GetParameters();
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(false);
System.Diagnostics.StackFrame[] frames = trace.GetFrames();

我想可以从堆栈帧中检索该值。

参数名称可以从

ParameterInfo[] info = MethodInfo.GetCurrentMethod().GetParameters();中找到

using System.Reflection;


ParameterInfo[] info = MethodInfo.GetCurrentMethod().GetParameters();
System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(false);
System.Diagnostics.StackFrame[] frames = trace.GetFrames();

i guess the value can be retrieved from stack frames.

The Paramter Name can be found from the

ParameterInfo[] info = MethodInfo.GetCurrentMethod().GetParameters();

小情绪 2024-10-15 04:47:50
public void Show(int value)
    {
        ParameterInfo[] info = MethodInfo.GetCurrentMethod().GetParameters();
        Trace.WriteLine(string.Format("{0} {1}={2}", info[0].ParameterType.ToString(), info[0].Name, value.ToString()));
    }

输出

System.Int32 值=10

public void Show(int value)
    {
        ParameterInfo[] info = MethodInfo.GetCurrentMethod().GetParameters();
        Trace.WriteLine(string.Format("{0} {1}={2}", info[0].ParameterType.ToString(), info[0].Name, value.ToString()));
    }

output

System.Int32 value=10

夜访吸血鬼 2024-10-15 04:47:50

尝试使用 PostSharp 它支持 Compact Framework。

Try using PostSharp it has the support for Compact Framework.

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