Visual Basic 中的共享类字段

发布于 2024-11-26 13:00:29 字数 900 浏览 1 评论 0原文

我有一个类 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我还不会笑 2024-12-03 13:00:29

我猜测,在出于发布目的而混淆此代码时,您掩盖了这样一个事实:您在页面加载中也声明了一个名为 MyClass 的变量(这就是错误的基本含义) )。

Visual Basic 是一种不区分大小写的语言。将变量声明为 myClass 与将其声明为 MYCLASSmyclass 相同,并且行 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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文