我有一个VB.net程序,我是从别人那里得到的。它由一个主表单和另外6个模块(所有.vb文件)组成。这些文件在资源管理器窗格中旁边都有一个“VB”图标。我试图在主窗体的一个模块中调用子例程。我的代码行是:
QuoteMgr.StartGettingQuotesLevel2(sSym)
其中QuoteMgr是模块的名称,StartGettingQuotesLevel2(sSym)是子例程的名称。当我输入这个时,我收到错误消息:
Reference to a non-shared member requires an object reference.
子例程在QuoteMgr模块中定义如下:
Public Sub StartGettingQuotesLevel2(ByVal oSymbol As String)
当我进入时,奇怪的是:
QuoteMgr.
(具有句点的模块的名称),它不会向我显示模块中的所有子例程和函数。它只显示:
Update_Level1
Update_Level12
Update_Level2
这些是模块中的Public Const。
你能告诉我我需要做什么吗?
答案 0 :(得分:3)
编译器试图通过此错误消息告诉您什么
对非共享成员的引用需要对象引用
StartGettingQuotesLevel2
子例程是 实例方法 而不是 共享 或类方法,请参阅更详细的解释here
要调用实例方法,您需要使用对象实例来调用它。在您的情况下,类类型的对象实例 QuoteMgr
。如下例所示:
' create a new QuoteMgr object instance
Dim myQuoteMgr As QuoteMgr = New QuoteMgr()
' call its instance method with "abc" as its oSymbol argument.
myQuoteMgr.StartGettingQuotesLevel2("abc")
您可能只希望主表单创建并使用单个QuoteMgr
对象实例。在这种情况下,您可以将其设为主表单的成员变量并创建一次。
Public Partial Class MainForm
' Create it as a private member variable of the main form
Private m_QuoteMgr As QuoteMgr = New QuoteMgr()
' Use it when "some" button is pressed
Private Sub btnSome_Click(sender As Object, e As EventArgs) Handles btnSome.Click
m_QuoteMgr.StartGettingQuotesLevel2(txtSymbol.Text)
' And possibly do something with the results.
End Sub
End Class
此外,如果QuoteMgr
类的实例依赖于其他对象实例来执行其任务,则必须将这些实例提供给QuoteMgr
类的构造函数方法, 参数为其构造函数的方法参数。构造函数(Sub New(...)
)看起来像这样:
Public Class QuoteMgr
' This is a constructor that takes two arguments
' - oMainSymbol: a string value
' - oKernel: an instance of the type Kernel
Public Sub New(oMainSymbol As String, ByRef oKernel As Kernel)
' ....
End Sub
End Class
这意味着,当您创建QuoteMgr
实例时,必须使用所需的内容调用其构造方法,例如
' There must be an instance of Kernel created somewhere.
Dim myKernel As Kernel = ....
' create a new QuoteMgr object instance with these arguments:
' - oMainSymbol = "SYMABC"
' - oKernel = myKernel
Dim myQuoteMgr As QuoteMgr = New QuoteMgr("SYMABC", myKernel)
其他一些建议
答案 1 :(得分:0)
右键单击您的应用程序,然后转到“属性”。 确保您的应用程序类型为" Windows Forms Application"。
答案 2 :(得分:-1)
这意味着您尝试调用的例程需要引用表单实例来访问例程。您可以像Alex所说的那样引用实例,也可以使例程“共享”,因此它不需要实例。为此,请将QuoteMgr.vb中的定义更改为
Friend Shared Sub StartGettingQuotesLevel2(ByVal oSymbol As String)
将其切换为“共享'如果例程访问表单控件或模块级变量,则可能会开始显示编译器错误。这些将需要添加到参数列表中。