我有一個Windows窗體應用程序,我試圖重構 - 我有一些函數和變量,我想分開到其他類。當我這樣做時,我無法訪問MainClass
的成員,就像Windows窗體的控件一樣。我可以讓它們變成靜態的,但是我遇到了設計師的問題。例如,在NewClass
功能我重構,我會參一控狀:Windows窗體中的重構代碼
MainClass.listBox1.Items.Clear();
但是,這不會工作,作爲控制是私有的。這給了錯誤:
1. An object reference is required for the non-static field, method, or property 'MainClass.listBox1'
2 'MainClass.listBox1' is inaccessible due to its protection level
所以,如果我做listBox1
公共靜態的,所以我NewClass
可以訪問它,我到處出現以下錯誤this.listBox1
出現在Designer.cs:
1 Member 'MainClass.listBox1' cannot be accessed with an instance reference; qualify it with a type name instead
所以我首先想到的是改變this.listBox1到MainClass.listBox1,但我認爲警告在Designer.cs頁面的頂部:
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
很明顯,這些不是我真正的代碼示例/名稱,但錯誤是我得到的,爲了泛化,我用適當的名稱替換了名稱。感謝大家!
我也見過這個;例如,在嘗試設置MainWindow的文本框時,我無法訪問它,並且使它公開有時可用,有時也不會(爲此,我將不得不編輯自動生成的文件)。一個潛在的解決方案將是一個「MainWindow」。ClearListBox1()'MainWindow'可以清除列表框的方法 – 2015-03-13 19:16:02
這不是關於重構,而是關於基本面向對象的原則。使事物靜態和公開不是一個好習慣,基本上是程序化編程。事實上,你正在讓事情變得更糟。 – 2015-03-13 19:30:10
@PhilipStuyck我並不是暗示將控件設置爲公開還是靜態是正確的行爲,只是因爲保護級別的訪問是給出的錯誤,所以自然而然地出現這些是前兩個想到的事情。我認爲沒有任何價值,我只是OOP的新手;我的目標是從我的錯誤和問題中學習。謝謝! – jacksonSD 2015-03-13 20:51:42