使用反射来获取参数的名称
我有 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果我没记错的话,反射是不可能的,因为变量名不在程序集中,而
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.我想可以从堆栈帧中检索该值。
参数名称可以从
ParameterInfo[] info = MethodInfo.GetCurrentMethod().GetParameters();中找到
i guess the value can be retrieved from stack frames.
The Paramter Name can be found from the
ParameterInfo[] info = MethodInfo.GetCurrentMethod().GetParameters();
输出
System.Int32 值=10
output
System.Int32 value=10
尝试使用 PostSharp 它支持 Compact Framework。
Try using PostSharp it has the support for Compact Framework.