开发者

using reflection to get the name of a parameter

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


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


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();


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


Try using PostSharp it has the support for Compact Framework.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜