以另一种形式访问类的同一实例 [英] Accessing the same instance of a class in another form

查看:168
本文介绍了以另一种形式访问类的同一实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信这是一个简单的问题,但我没有足够的经验知道答案。 :)

  DataClass,Form1,Form2 

我有一个公共类, DataClass ,在一个单独的文件中, DataClass.vb 。在 DataClass 我有数据存储在几个数组,我需要访问。我在 DataClass 中有方法,以便我可以访问数据。其中一个是 GetName 。一切都在 Form1 上正常工作。我需要在另一个表单上访问数组中的相同数据,但是我需要调用该类的一个新实例,因此当我调用方法访问数组时,数据为空。



我已经看到一些线程提到创建一个 singleton类,但大多数是关于C#,我不熟悉。 >

最佳做法是什么?

解决方案

可以做到这一点。
其中一个将涉及创建一个模块,然后使用变量实例化您的类 Public 模块:

 模块MyGlobalVariables 
Public MyDataClass As DataClass
结束模块

现在,您项目中的所有表单都将能够通过 DataClass MyGlobalVariables.MyDataClass






您的Form2中可设置为 DataClass 实例的属性:

 公共属性MyDataClass As DataClass 

然后,您将实例化 Form2 如下(假设您在 Form1 中用于实例化 DataClass 的变量称为 _dataClass ):

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






最后,另一种方法是重写 Form2 的构造函数,并允许它接收 DataClass 。然后,您可以将 Form2 实例化为:

  Dim frm2 As New Form2 (_dataClass)

希望这有助于...


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?

解决方案

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

这篇关于以另一种形式访问类的同一实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆