MVC Winforms c# nullreferenceexception

MVC Winforms c# nullreferenceexception

我是一个尝试在 C# winforms 中学习 mvc 的菜鸟,但我似乎无法理解为什么我的实例对我变为 null。

查看表格

 public partial class Form1 : Form, ISingleTagProperties
{
   .....        
    PropController _propController;

    public void SetController(PropController controller)
    {      
        _propController = controller;
    }
.....
   private void dataGridView3_CurrentCellChanged(object sender, EventArgs e)
   {
       _propController.updateProperites(dgv);
   }

编辑:调用 updateProperties 给我空引用。

控制器 PropController class

public class PropController
{
     SingleTagProperties _view;

    //constructor
    public PropController(SingleTagProperties view)
    {
        _view = view;
        view.SetController(this);
    }
......

查看实例 ISingleTagProperties

 public interface ISingleTagProperties
{
    void SetController(PropController controller);

    string TagName { get; set; }
    string TagDescription { get; set; }
.....

SetController 触发并且 _propController 不为空,但随后在表单中进一步尝试从 PropController 调用方法 class 给出 NullReferenceException 说 _propController 为空。

我可能缺少一些基本的理解,但我似乎无法理解。

您在工作中使用了错误的工具...

如果你想学习 MVC,请使用 ASP.NET MVC (Model View Controller),如果你想学习适合桌面/移动应用程序开发的设计模式,请使用 WPF 和学习 MVVM (Model View ViewModel).

这是您可以学习的优秀资源:

PluralSight: ASP.NET MVC 5 - Fundamentals

事件的顺序必须是:

  1. 表单已创建。
  2. ...
  3. 您创建视图,将表单作为构造函数参数传递,这会设置 _propController。

当您创建表单时,所有其他控件也可能被创建(通常通过在构造函数中调用工具为您生成的部分 class 中的方法)。

这实际上是上面的第 3 步,我怀疑初始化这些控件的过程正在触发该事件。因为那发生在第 2 步之前,所以未设置 _propController。

尽管从视图中引用控制器似乎破坏了您想要实现的 MVC 分离,但您可能想要进行空值检查或其他解决方法。