2013-10-12 64 views
0

我在我的意見徹底尋找在這個網站的答案,但不幸的是我還沒有找到任何或我只是看着它吮吸。如何引用來自不同形式的現有引用對象?

我有2個窗體和1個控制器類和1個模型類或數據類。另外,ControllerClass有一個模型類的數組。

Form1我不喜歡這對控制器的引用:

ControllerClass control = new ControllerClass(); 

Form2我想從ControllerClass我在Form1稱爲參考。

到現在爲止我一直在做這樣的事情:

ControllerClass control = new ControllerClass(); 
Form2

,但這只是使ControllerClass的新副本,這是不是對我很有幫助。

那麼我怎樣才能使用ControllerClass,我在Form1中實例化了Form2

+1

http://stackoverflow.com/questions/2957388/passing-object-to-different-windows-forms,http://stackoverflow.com/questions/4887820/how-do-you-pass-an-object從表單1到表單2和回到表單1,http://stackoverflow.com/questions/1665533/communicate-between-two-windows-forms-in-c-sharp – Corak

+1

只需將對象作爲Form2(Form2 f2 = new Form2(control);')的構造函數中的一個參數,或者創建一個公用屬性,然後填充對象引用。 –

回答

-1

如果您不想通過構造函數(Communicate between two windows forms in C#)將對象傳遞給其他窗體,如其他人在此處所建議的那樣,則可以在Form1中使用靜態對象。

例如,你可以聲明

public static ControllerClass control = new ControllerClass(); 

,然後訪問喜歡的對象:

ControllerClass temp = Form1.control; 

你也可以做一個第二,靜態類將有ControllerClass對象(類應該在相同的名稱空間中,而不是在Form1類中),如下所示:

public static class ControllerStaticClass 
{ 
    public static ControllerClass control = new ControllerClass(); 
} 

Th恩,你可以訪問ControllerClass對象,如:

ControllerClass temp = ControllerStaticClass.control; 
+0

它給了我一個錯誤,說Inconsistent可訪問性字段類型ControllerClass比字段form1更難以訪問。 –

+0

Form1類應該是公開的(我已經修改了我的答案)。 –

0

如果你只需要一個對象從一個類,你可以使用一個單例。然後ofc,你將永遠擁有同一個對象。

有幾種方法,你如何實現你的控制作爲一個單身

這裏一些例子: http://csharpindepth.com/articles/general/singleton.aspx

對於C#我喜歡嵌套的版本。