方法或操作未实现

The method or operation is not implemented

有两种形式。 Form2 派生自 Form1.

但是我在设计模式下遇到 Form2 的问题,如下面的屏幕截图所示。

如果我评论这个 this._presenter.Retrive(); 它会很好用。怎么回事,怎么解决?

更新: 如果我将删除 throw new NotImplementedException();并会插入,例如,MessageBox.Show("Test");,每次我打开 Form2 时,MessageBox 都会出现,就像我 运行 应用程序一样。

Form2

namespace InheritanceDemo
{
    public partial class Form2 : Form1
    {
        public Form2()
        {
            InitializeComponent();
        }
    }
}

Form1

namespace InheritanceDemo
{
    public partial class Form1 : Form
    {
        protected IPresenter _presenter;

        public Form1()
        {
            InitializeComponent();
            _presenter = new Presenters();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this._presenter.Retrive();
        }
    }

    public class Presenters : IPresenter
    {
        public void Retrive()
        {
            throw new NotImplementedException();
        }
    }

    public interface IPresenter
    {
        void Retrive();
    }
}

Whats going on and how to solve the problem?

这很简单。如果你想调试你的代码,你会看到你在你的方法调用中抛出一个 NotImplementedException,这就是注释掉它的原因:

public void Retrive()
{
    throw new NotImplementedException();
}

也许您想实现实际的方法逻辑而不是抛出。

错误的主要原因是 and 所说的:

throw new NotImplementedException();

但是还有一个重要的事情你应该注意。

OP: If I will remove the throw new NotImplementedException(); and will insert, for example, MessageBox.Show("Test");, every time I will open Form2 the MessageBox will appears as though I run the application

如果您注意到,您将不会在 Form1 的设计器中收到此错误。但是因为你的 Form2 继承自 Form1 你会收到这个错误。

这是因为,当您在设计器中打开一个表单时,设计器会在您的表单的base class 中创建一个实例来显示您的表单。这意味着不是创建 Form2 的实例,而是创建 Form1 的实例,运行 Form1 构造函数并将其托管在设计表面,然后反序列化 InitializeComponent 中的代码Form2 并将组件放在设计图面上。

这就是为什么当您在设计器中看到 Form2 时收到错误,但在设计器中打开 Form1 时却没有收到任何错误的原因。

解决问题:

  • 您可以删除实现,让实现为空。
  • 您还可以通过防止运行 Form_Load 中的代码来防止错误,fd 您正处于使用DesignMode 属性 的设计模式,在Form1_Load:

    if(设计模式) return;

您可能会发现这些答案既有用又有趣:

注释掉 部分 throw new NotImplementedException(); 对我来说效果很好 现在,最终方法将与下面类似:

public void Retrive()
{
    //throw new NotImplementedException();
}