Shared class field in Visual Basic

2019-09-14 22:39发布

问题:

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.