如何从vb.net中的模块访问表单变量 [英] How do you access form variable from a module in vb.net
本文介绍了如何从vb.net中的模块访问表单变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从vb.net中的模块访问表单变量?
解决方案
将表单变量声明为public.
<首先,应将变量声明为public
(从不同程序集的同一程序集访问)或internal
(从同一程序集的访问,因此应更频繁地使用).该变量"实际上应该是成员,可以是字段,也可以是属性.通常,正确的封装要求它是属性,而不是字段.从外部访问任何字段都被认为是不好的编码风格.
如果成员是static
,则可以从外部以MyModule.MyMember
身份访问它.如果这是一个实例成员(非静态),则需要具有该模块的实例(通过在某个地方调用的构造函数,该实例将返回对该实例的引用),并以MyInstance.MyMember
的形式进行访问.
如果不引用该类的实例,则无法直接访问该类.您最好的选择可能是这样的:
模块 Module1 私有 m_MyForm As Form1 公共 只读 属性 MyForm() As Form1 获取 如果 IsNothing(m_MyForm)然后 m_MyForm = 新建 Form1 返回 m_MyForm 结束 获取 结束 属性 公共 子 WriteLog( ByVal txt As 字符串) MyForm.TextBox3.Text + = txt + vbNewLine 结束 子 结束 模块
现在,您可以在应用程序中的任何位置使用Module1.MyForm访问Form1.
How do you access form variable from a module in vb.net?
解决方案
Declare the form variable as public.
First, the variable should be declaredpublic
(to access from the same of different assembly) orinternal
(to access from the same assembly, so it should be used more often). This "variable" is actually should be a member, either a field or a property. Usually, proper encapsulation requires it to be a property, not a field. Having any fields accessible from outside is considered a bad coding style.
If the member isstatic
, you access it from outside asMyModule.MyMember
. If this is an instance member (non-static), you need to have an instance of the module (via a constructor you call somewhere which returns you the reference to the instance), and access it asMyInstance.MyMember
.
—SA
You cannot directly access a class without a reference to an instance of that class. Your best bet might be something like this:
Module Module1 Private m_MyForm As Form1 Public ReadOnly Property MyForm() As Form1 Get If IsNothing(m_MyForm) Then m_MyForm = New Form1 Return m_MyForm End Get End Property Public Sub WriteLog(ByVal txt As String) MyForm.TextBox3.Text += txt + vbNewLine End Sub End Module
Now anywhere in your application you can access Form1 using Module1.MyForm.
这篇关于如何从vb.net中的模块访问表单变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文