Visual Basic 中的共享类字段
我有一个类 MyClass
,声明为 public,具有 Shared
方法 test()
:
Public Class MyClass
Public Shared Function test()
Return "sdfg"
End Function
' snip other non-shared methods
End Class
这个 Class
是位于网站的 App_Code 目录中,并且似乎是可见的,因为我可以从任何网站脚本实例化该类的实例。
我的问题特别与访问 Shared
方法 test()
相关。为了使其正常工作,我在其中一个脚本的 Page_Load()
中有以下代码:
Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)
Response.Write MyClass.test()
Dim myClassVar As MyClass = new MyClass()
myClassVar.nonSharedMethod()
End Sub
如果我注释掉 Response.Write MyClass.test()
,一切正常很好,我可以使用 Class
- 但是,尝试访问 Shared
方法时,我收到以下错误:
Local variable 'myClass' cannot be referred to before it is declared
有任何关于我做错了什么的指示吗?
I have a class, MyClass
, declared as public, with a Shared
method test()
:
Public Class MyClass
Public Shared Function test()
Return "sdfg"
End Function
' snip other non-shared methods
End Class
This Class
is located in the App_Code
directory of the website, and appears to be visible, as I can instantiate an instance of the Class from any of the sites scripts.
My issue relates specifically to accessing the Shared
method test()
. Trying to get this working, I have the following code in Page_Load()
of one of the scripts:
Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)
Response.Write MyClass.test()
Dim myClassVar As MyClass = new MyClass()
myClassVar.nonSharedMethod()
End Sub
If I comment out Response.Write MyClass.test()
, everything works fine and I can use the Class
- however, trying to access the Shared
method, I get the following error:
Local variable 'myClass' cannot be referred to before it is declared
Any pointers as to what I am doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我猜测,在出于发布目的而混淆此代码时,您掩盖了这样一个事实:您在页面加载中也声明了一个名为
MyClass
的变量(这就是错误的基本含义) )。Visual Basic 是一种不区分大小写的语言。将变量声明为
myClass
与将其声明为MYCLASS
或myclass
相同,并且行MyClass.test() 会将名称
MyClass
解析为该变量 - 正如错误所示,该变量尚未声明。I'm guessing that in obfuscating this code for posting purposes, you've masked the fact that you have a variable with the name
MyClass
also declared in your page load (that is what the error is basically saying).Visual Basic is a case insensitive language. Declaring your variable as
myClass
is the same as declaring it asMYCLASS
ormyclass
, and the lineMyClass.test()
will be resolving the nameMyClass
to that variable - which as the error indicates, hasn't been declared yet.