Accessing the same instance of a class in another form

拜拜、爱过 提交于 2019-12-06 11:59:27

问题


I'm sure this is a simple question, but I don't have enough experience to know the answer. :)

DataClass, Form1, Form2

I have a public class, DataClass, in a separate file, DataClass.vb. In DataClass I have data stored in several arrays that I need to access. I have methods in DataClass so that I can access the data. One of them is GetName. Everything works fine on Form1. I need to access the same data in the arrays on a another form, but I am required to call a new instance of the class, so when I call the methods to access the arrays, the data is empty.

I've seen some threads mention creating a singleton class, but most are about C# which I am not as familiar with.

What is the best practice?


回答1:


There are many ways in which you can do this. One of them would involve creating a Module and then making the variable that instantiates your class Public inside the module:

Module MyGlobalVariables
    Public MyDataClass As DataClass
End Module

Now, all the forms in your project will be able to access the DataClass via MyGlobalVariables.MyDataClass.


A preferable method would be to add a property to your Form2 that can be set to the DataClass instance:

Public Property MyDataClass As DataClass

Then, you would instantiate your Form2 as follows (assuming the variable you use to instantiate DataClass in Form1 is called _dataClass):

Dim frm2 As New Form2()
frm2.MyDataClass = _dataClass
frm2.Show()

And finally, another way would be to override the constructor of Form2 and allow it to receive a parameter of type DataClass. Then, you could instantiate Form2 as:

Dim frm2 As New Form2(_dataClass)

Hope this helps...




回答2:


You can create a singleton class like this

Public Class DataClass
    Public Shared ReadOnly Instance As New DataClass()

    Private Sub New()
    End Sub

    ' Other members here
End Class

You can access a single instance through the shared Instance member which is initialized automatically. The constructor New is private in order to forbid creating a new instance from outside of the class.

You can access the singleton like this

Dim data = DataClass.Instance

But this is not possible

Dim data = new DataClass() 'NOT POSSIBLE!

Since the singleton class is accessed through the class name, you can access it from the two forms easily.



来源:https://stackoverflow.com/questions/14419516/accessing-the-same-instance-of-a-class-in-another-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!