确定这个错误的原因,复选框c#

本文关键字:复选框 错误 | 更新日期: 2023-09-27 17:50:17

大家好,我很难理解为什么有些代码会崩溃。有问题的指令如下:

第一次尝试:

        bool aers = vm_SessionTab.IncrementalConstruction; // != null
        bool chua = IncrementalCB.Checked;                 // != null
        if (aers) IncrementalCB.CheckState = CheckState.Checked; // crash, null reference exception

第二次尝试:

        bool aers = vm_SessionTab.IncrementalConstruction; // != null
        bool chua = IncrementalCB.Checked;                 // != null
        IncrementalCB.Checked = vm_SessionTab.IncrementalConstruction //crash, null reference exception

IncrementalCB是一个复选框。vm_SessionTab是一个包含我想要显示的状态的个性化对象。当我进入调试器时,我发现"aers"answers"chua"不同于null。然后在接下来的两次尝试中,程序崩溃告诉我它发生了一个空引用异常。我在问这是怎么发生的。我明确地检查这两个值是否不同于null:S。完整的代码相当大,但这些是相关的行。

更多信息:

我真的很确定IncrementalCB是!= null,但如果我在我显示的代码之前创建另一个复选框,那么就不会抛出异常,并且控件正确显示。为什么我需要重新创建的控制,如果它已经存在?如此:

        IncrementalCB = new CheckBox();         //i think this is unnecesary, it exists.
        bool aers = vm_SessionTab.IncrementalConstruction;
        bool chua = IncrementalCB.Checked;
        if (aers) IncrementalCB.CheckState = CheckState.Checked;

添加…

谢谢大家建议我看看stacktrace。在这一点上我看到了我所犯的可怕的错误。在伪代码解释中,这是我的错误:(我尝试应用MVVP模式)

Call the View Constructor
   Create the Presenter that manage the view.
       at the end of the Presenter constructor i callback a method to show in the View the basic UI elements.
      callback:                                           . 
      in the view i load differents UI elements           ... presenter contructor not yet finalized
      i modify the value of the checkbox, trying to do it ...
        directly.
 ERROR->the modification is not realized directly and the ...
        event handler of the Checked_Changed event is raised.
        The presenter has te responsability to perform    ...
        the change, but.................................> ... presenter constructor not yet finalized 

因此,当要求尚未完成的演示者完成更改时,结果是Null引用异常。由于我没有访问内部Checked字段来进行直接更改,而没有事件Checked_Changed被引发,我需要移出回调。这个错误有点难以看到,因为当我在调试器中使用f11跳入时,事件处理程序的调用没有显示,所以我只看到直到每个对象都以很好的方式执行其操作

确定这个错误的原因,复选框c#

的行。

看起来IncrementalCB就是null。当您尝试执行代码时,它是否已初始化?

当您试图访问其Checked属性时,看起来CheckState变量为空:

CheckState.Checked