簡體   English   中英

為什么以下代碼會產生對象處置異常

[英]Why does the following code produce Object Disposed Exception

我在Visual Studio中玩耍,並逐漸了解C#。 我來自Java的中級背景知識。

我制作了一個非常簡單的Windows窗體應用程序。 用戶單擊一個按鈕,該按鈕將它們帶到另一個屏幕,用戶在文本框中鍵入內容,然后按下一個按鈕,該按鈕將顯示用戶鍵入的內容; 的形式。 這是代碼:

Form1.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form


    {
        Form2 userinputForm;
        public Form2 getSetForm2 {
            get { return userinputForm; }
            set { userinputForm = value; }
        }

        Form1 homeFormObj;
        public Form1 getSetForm1 {
            get { return homeFormObj; }
            set { homeFormObj = value; }
        }



        public Form1()
        {
            InitializeComponent();
            getSetForm2 = new Form2();
            getSetForm1 = this;
            getSetForm2.formOnePublicObj = getSetForm1;
        }

        internal void displayUserInput(string name)
        {
            Label l = new Label();
            l.Text = name;

            panel1.Controls.Add(l);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            userinputForm.Show();
        }
    }
}

Form2.cs:

    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form2 : Form
    {
        Form1 formOneObj;
        public Form1 formOnePublicObj {
            get { return formOneObj; }
            set { formOneObj = value; }
        }

        public Form2()
        {
            InitializeComponent();
        }

        List<string> userinputs = new List<string>();

        private void button1_Click(object sender, EventArgs e)
        {
            string name = textBox1.Text;
            formOnePublicObj.displayUserInput(name);

        }
    }
}

該錯誤發生在用戶第二次按下按鈕進入form2時。 它發生在.show()方法上。

(PS我這樣編碼,以查看如何將數據從一個窗口表單傳遞到另一個窗口,從而傳遞表單對象上的獲取器和設置器)。

好吧,從不設置userinputform ,所以為null 因此,我不明白為什么它第一次起作用,除非這實際上不是您粘貼的代碼。

可能是因為您要關閉第二個表單,這正在銷毀它,因此您無法再次顯示它。 每次您在form1中單擊按鈕時,都會創建一個新的form2:

        getSetForm2 = new Form2();
        getSetForm1 = this;
        getSetForm2.formOnePublicObj = getSetForm1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM