跨多个项目文件访问模块变量/方法

时间:2015-08-06 14:39:13

标签: vb.net variables methods module

我正在开发一个在其基础项目文件中使用模块的系统。在创建新项目时,基础项目文件的模块中引用的变量/方法需要可用于新项目。这里的最佳做法是什么?我以前从未使用过模块和我正在做的所有阅读以开始旋转我的脑袋。

这是我想要完成的一个简化版本。如果我需要构建一个全新的方法并将所有项目移出模块并进入任何和所有现有/新项目文件可用的某种形式的类结构,那么就这样吧。我可以返回并更新现有的代码库以引用新的类结构。

MainProjectFile.vb (this is a snapshot of the existing Module)
    Module mdlMain
        Friend userID as integer
        Friend key as integer
        Friend tabCounter as integer
        ...
        ...
    End Module


NewProjectFile.vb
    public class createNewTab
         public sub new()
              'need to access tabCounter in the module back in the main project file
               mdlMain.tabCounter =+ 1
         end sub
    end class

1 个答案:

答案 0 :(得分:0)

您可以使用关键字Public,Private,Protected,Friend (see MSDN)设置模块的访问级别及其方法。如果您的示例代码在同一个项目中,那么您应该已经拥有所需的访问权限(friend修饰符意味着同一项目中的所有代码都可以访问tabCounter变量)。

如果您使用Public作为模块的前缀,则几乎任何人都可以访问该模块,甚至是在单独项目中定义的代码(使用对包含模块的项目的引用)。

如果您来自另一种语言,您可以将模块视为一个类,其中所有成员都被声明为静态(在VB术语中共享)和一个限制您的私有构造函数用它作为单身人士。

此代码:

Public Module Module1
   Public Sub SampleMethod()
      'Do something interesting here
   End Sub
End Module

可以翻译成:

Public Class Module1
   Private Sub New()
   End Sub

   Public Shared Sub SampleMethod()
      'Do something even more interesting here
   End Sub
End Class

还有更多的事情发生在幕后。模块允许您在不完全限定成员的情况下访问成员。另一方面,类要求您至少指定类名。

'Using your code example
public class createNewTab
     public sub new()
          'need to access tabCounter in the module back in the main project file
           mdlMain.tabCounter =+ 1
          'no need to use the module name unless there's another module with the same member
           tabCounter = 42
     end sub
end class