Accessing the same instance of a class in another

2019-04-14 00:22发布

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?

2条回答
该账号已被封号
2楼-- · 2019-04-14 01:15

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...

查看更多
Explosion°爆炸
3楼-- · 2019-04-14 01:16

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.

查看更多
登录 后发表回答