创建对象的新实例后保留以前的数据

时间:2013-03-27 19:25:05

标签: .net vb.net variable-declaration objectinstantiation

说我有这个:

Dim Editor As frmEditor
Editor.Text = "New Form"
Editor.Controls.Add(richTextBox)

然后在子例程中,我这样做:

Editor = New frmEditor

是否可以保存先前声明的Editor的控件/数据以备将来使用?声明的那个不是使用New关键字实例化的那个。

2 个答案:

答案 0 :(得分:1)

[nkvu - 如果有人有类似的查询,请从评论转移到答案....]

你可以这样做:

Dim oldEditor as frmEditor 

然后在你做之前:

Editor = New frmEditor 

这样做:

oldEditor = Editor
然后

oldEditor应该引用前一个对象

答案 1 :(得分:1)

Dim Editor As frmEditor

...不创建编辑器,它只声明一个空变量,因此......

Dim Editor As frmEditor
Editor.Text = "New Form"

......会失败!

必须使用New创建表单:

Dim Editor As frmEditor
Editor = New frmEditor()
Editor.Text = "New Form"

或者

Dim Editor As frmEditor = New frmEditor()
Editor.Text = "New Form"

回答你的问题:

将“旧”编辑器分配给另一个变量

Dim oldEditor As Editor = frmEditor
frmEditor = New frmEditor()
frmEditor.RtfText = oldEditor.RtfText

还创建一个公共属性,允许您从表单外部访问您需要访问的内容

Public Property RtfText() As String
    Get
        Return richTextBox.Rtf
    End Get
    Set(ByVal value As String)
        richTextBox.Rtf = value
    End Set
End Property