全局变量返回意外值

时间:2012-12-27 08:25:51

标签: c# wpf variables global

我试图分配全局变量来从复选框和单选按钮读取值,但是当选择更改时,值不会更新!我哪里做错了?这是代码:

private void chkInMut_Checked(object sender, RoutedEventArgs e)
    {
        GlobalVar.Mutate = 1;
    }

    private void chkShwCal_Checked(object sender, RoutedEventArgs e)
    {
        GlobalVar.ShowCal = 1;
    }

    private void chkOutSol_Checked(object sender, RoutedEventArgs e)
    {
        GlobalVar.OutCal = 1;
    }
}

public static class GlobalVar
{
    static int _MaxMin, _MutVal, _CalShow, _CalOut;

    /// <summary>
    /// Access routine for global variable.
    /// </summary>

    public static int Extrema
    {
        get
        {
            return _MaxMin;
        }
        set
        {
            _MaxMin = value;
        }
    }

    public static int Mutate
    {
        get
        {
            return _MutVal;
        }
        set
        {
            _MutVal = value;
        }

    }

    public static int ShowCal
    {
        get
        {
            return _CalShow;
        }
        set
        {
            _CalShow = value;
        }
    }

    public static int OutCal
    {
        get
        {
            return _CalOut;
        }
        set
        {
            _CalOut = value;
        }
    }
}

当我尝试使用此测试声明打印数字时,返回的值是意外的:

        maxMin = GlobalVar.Extrema;
        calShow = GlobalVar.ShowCal;
        calOut = GlobalVar.OutCal;
        IsMutble = GlobalVar.Mutate;
        txtOutput.Text += Convert.ToString("\nMaxima Minima"+maxMin+"\n"+"Show Cal : "+calShow+"\n"+"Output Cal :"+calOut+"\n"+"Mutate : "+IsMutble+"\n---------\n");

当我选中/取消选中复选框时,值不会更新。我哪里出错?

编辑:添加未经检查的参数解决。

2 个答案:

答案 0 :(得分:1)

可能你应该写这样的事件处理程序

private void chkInMut_Checked(object sender, RoutedEventArgs e)
{
    GlobalVar.Mutate = (chkInMut.IsChecked ? 1 : 0);
}

依旧.....

答案 1 :(得分:0)

我认为问题出在你的公共静态属性上。例如试试这个:

public static int Extrema
{
    get
    {
        return GlobalVar._MaxMin;
    }
    set
    {
        GlobalVar._MaxMin = value;
    }
}

并对所有其他属性执行相同的操作。

修改 你为什么要用这个结构?您可以将静态类设置为:

public static class GlobalVar
{
   public static int Extrema;
   public static int Mutate;
     public static int ShowCal;
}