簡體   English   中英

使用屬性在表單之間傳輸數據

[英]Using properties to transfer data between forms

我正在嘗試使用屬性將兩個集合從一個轉移到另一種形式。 但是由於某種原因,我無法在form1中看到來自form2的屬性。 我收到的錯誤消息是

System.Windows.Forms.Form不包含_col1的定義,並且沒有擴展方法_col1接受類型為System.windows.Forms.Form。的第一個參數。

這是來自Form1的代碼

 public partial class Form1 : Form
 {

    private Collection<string> col1;
    private Collection<string> col2;

    private void btn1_Click(object sender, EventArgs e)
    {
        Form frm1 = new Form2();

        //fill collections with some kind of data

        frm1._col1 = _col1;
        frm1._col2 = _col2;

        frm1.Show();
    }
    public Collection<string> _col2
    {
        get { return col2; }
    }

    public Collection<string> _col1
    {
        get { return col1; }
    }
 }

這是來自Form2的代碼

public partial class Form2 : Form
{
    private Collection<string> col1;
    private Collection<string> col2;        

    public Form2()
    {
        InitializeComponent();
    }

    public Collection<string> _col1
    {
        get { return col1; }

        set { col1 = value; }
    }

    public Collection<string> _col2
    {
        get { return col2; }

        set { col2 = value; }
    }
}

根據文章,我閱讀了所有內容,但我無法從Form1訪問Form2屬性。

我想念什么?

您已經這樣聲明了frm1變量:

Form frm1 = new Form2();

因此,編譯器將假定其為Form類型。 正如錯誤消息正確解釋的那樣, Form沒有任何名為_col1屬性或方法。

如果將變量聲明為屬於Form2類型,則編譯器將找到您的屬性:

Form2 frm1 = new Form2();

CoderDennis所述 ,您還可以使用var關鍵字,而不是顯式聲明變量的類型:

var frm1 = new Form2();

但是請注意, C#編程指南警告:

但是,使用var確實至少有潛力使您的代碼更難以為其他開發人員所理解。 因此,C#文檔通常僅在需要時才使用var。

只要var不能替代真正繁瑣的代碼(例如泛型類型),對於一般的代碼來說,這並不是一個不明智的想法。


關於編碼風格的說明:約定將屬性以大寫字母開頭,因此您可能希望將屬性從_col1_col2分別重命名為Col1Col2

然后,如果您想在視覺上清楚地將屬性與私有后備字段區分開,請在CoderDennis在其注釋中正確指出的下划線放在私有字段的名稱中。

如下更新參考:

Form2 frm1 = new Form2();

col1在Form2類中確定。 由於Form1和Form2類具有相同的屬性,因此您可以考慮創建一個

interface IFormWithCollection
{
Collection<string> _col1
    {
        get;
        set;
    }

    Collection<string> _col2
    {
        get;  set;
    }
}

然后實現Fom1和Form2定義: Form1 : Form, IFormWithCollection

Form2 : Form, IFormWithCollection

接着:

IFormWithCollection frm1 = new Form2();

暫無
暫無

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

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