如何获取构造函数中的所有变量列表或变量值?

时间:2014-05-20 00:56:08

标签: c# winforms logging

例如我在构造函数中有这个:

countDown = 0;
            Client.CachePolicy = policy;
            SatelliteClient.CachePolicy = policy;
            btn8 = new Button();
            btn8 = button8;
            timer11 = new System.Windows.Forms.Timer();
            timer11.Interval = 1000;
            timer11.Enabled = false;
            timer11.Tick += new EventHandler(timer11_Tick);
            automaticDoubleClick = false;
            this.MouseWheel += new MouseEventHandler(Form1_MouseWheel);
            label18.Visible = false;
            filesSizeButtonSwitch = false;
            filesSizeDemoMode = false;
            paintDemoButtonSwitch = false;
            paintDemoMode = false;
            debugButtonSwitch = false;
            debugMode = false;
            timerdelay = 0;

这是我在构造函数中所拥有的一小部分。 我也有一个记录器,我使用这样的记录器:

Logger.Write("test");

我想要的是为每个变量vlaue键入Logger.Write来做一些循环,它将遍历所有变量自动获取值并将它们自动写入Logger。 仅举例:

Logger.Write(variables[i].ToString()); 

像这样。

反正有吗?我正在使用WinForms Application。

2 个答案:

答案 0 :(得分:0)

为当前帧创建StackFrame对象,调用GetMethod获取当前方法的MethodInfo对象,调用其GetMethodBody方法获取{{1} }}然后使用MethodBody属性。我不知道所有细节,因为我自己从未做过,但那是你应该开始寻找的地方。

更新:我进一步调查了一下,看起来我的建议无济于事,因为LocalVariables集合中的LocalVariableInfo个对象包含有关局部变量但不包含其值的数据或者得到他们的价值观。

答案 1 :(得分:0)

一个简单的想法是在中添加新方法,您可以在其中指定构造函数中使用的每个变量。这不是自动的,但有效:

    private string GetVariables()
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("timer11 = " + this.timer11.Interval.ToString() + "\n");
        sb.Append("timer11 = " + this.timer11.Enabled.ToString() + "\n");
        sb.Append("automaticDoubleClick = " + this.automaticDoubleClick.ToString() + "\n");
        sb.Append("label18.Visible = " + this.label18.Visible);
        // Add all needed variables ->

        return sb.ToString();
    }

然后,例如,您可以在对象中使用Logger,如下所示:

Logger.Write(this.GetVariables()); 

或在外面:

Logger.Write(YourObject.GetVariables());