Shared class field in Visual Basic

余生颓废 提交于 2019-12-11 16:41:36

问题


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?


回答1:


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 as MYCLASS or myclass, and the line MyClass.test() will be resolving the name MyClass to that variable - which as the error indicates, hasn't been declared yet.



来源:https://stackoverflow.com/questions/6830825/shared-class-field-in-visual-basic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!