2012-07-31 50 views
-1

可能重複:
Cloning objects in C#創建窗體對象不參考

我的代碼:

private void button1_Click(object sender, EventArgs e) 
{ 
    CopyForm(new Form1()); 
} 

public void CopyForm(Form form) 
{ 
    Form frm = form; 
    frm.Text = "1"; 
    form.Text = "2"; 

    string c = frm.Text;// out 2 
    string c2 = form.Text;// out 2 
} 

如何從表格without Ref創建對象?

請給我看看最好的方法。

編輯:

請樣品。

+2

看一看這裏 http://stackoverflow.com/questions/78536/cloning-objects-in-c-sharp – JohnnBlade 2012-07-31 06:12:31

+0

不知道它是什麼你是問。 「如何從表單創建沒有引用的對象」是什麼意思? – Maarten 2012-07-31 06:19:42

+0

從沒有參考的表單創建對象。 – user1329714 2012-07-31 06:24:35

回答

2

您可以使用Copy Constructor或使用ICloneable's Clone method的maka副本。

下面給出了複製構造函數的一個簡單示例。您需要創建自己的表單類並向其添加copyConstructor方法。

class MyClonableForm:Form 
{ 

public MyClonableForm(Form oldForm)//Copy Constructor 
{ 
this.Text=oldForm.Text; 
//write your clone code here 
//be careful with reference types! 
} 

} 

注意

不推薦使用ICloneable接口的,因爲它沒有指定克隆的類型來執行,即深或淺。

如果你確實想使用它,你可以但不公開公開的方法克隆。使用它爲你自己的目的!

+0

我認爲在這種情況下,它會好的。 – jamesbar2 2012-07-31 06:27:29

+0

@ jamesbar2是的..這將是好的... – Anirudha 2012-07-31 06:28:24

+0

沒有幫助。請幫助更多 – user1329714 2012-07-31 06:28:43