Visual Basic 中的共享类字段 [英] Shared class field in Visual Basic

查看:35
本文介绍了Visual Basic 中的共享类字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,MyClass,声明为 public,带有一个 Shared 方法 test():

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

这个 Class 位于网站的 App_Code 目录中,并且看起来是可见的,因为我可以从任何站点脚本实例化一个 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.

我的问题特别涉及访问 Shared 方法 test().为了让这个工作,我在其中一个脚本的 Page_Load() 中有以下代码:

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

如果我注释掉 Response.Write MyClass.test(),一切正常,我可以使用 Class - 但是,尝试访问 Shared 方法,我收到以下错误:

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?

推荐答案

我猜想,为了发布目的而混淆了这段代码,你掩盖了你有一个名为 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 是一种不区分大小写的语言.将变量声明为 myClass 与将其声明为 MYCLASSmyclass 以及 MyClass.test() 会将名称 MyClass 解析为该变量 - 正如错误所示,尚未声明.

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.

这篇关于Visual Basic 中的共享类字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆