从外部.vb文件导入/调用类 vb.net



我有一个相当大的 VB.net 代码,我正在尝试将其拆分为不同的文件。我想创建一个包含不同功能的外部文件。我已经阅读了有关部分类文件的信息,但它对我不起作用。是否有任何选项可以调用/导入 vb.net 文件并按照以下示例执行某些操作?


表格1.vb


' Imports Functions.vb (How can I call the file containing the class?)
Public Class Form1
Dim a,b,y As Double
Dim calculate As New MyFunctions
a=1
b=1
y=calculate.sum(a,b)
End Class

功能.vb


Partial Class MyFunctions
Public Function sum(a As Double, b As Double) As Double
     return a+b
End Function
End Class

如果您希望所有函数都可用于所有代码,只需创建一个包含函数的模块。

如果你只想将 form1 类拆分为单独的文件,你的 form1 文件应该包含类定义。

Partial Public Class Form1

要为要分离的位创建新文件,请创建一个新的类文件并将默认定义更改为上述定义。

请注意,您可能还需要为每个文件添加Imports行。

在我的旧项目中,我有一个表单程序,但将代码拆分为多个文件,例如 ExcelFileHandling.vb、EmailHandling.vb 等。它们实际上都是 Form1 的部分定义。简单易行:-(

当您不想完全限定类的命名空间时,可以使用 Imports 语句。 如果另一个类与引用它的类位于同一命名空间中,则无需使用 Imports。 请注意,示例代码具有应存在于方法中而不是类主体中的功能。

'RootNamespace = Right click on project file and choose properties.  You'll see it defined there.
Imports RootNamespace.SomeOtherNamespace
Namespace SomeNamespace
    Public Class Form 1
        Public Sub SomeMethod()
            Dim objMyFunctions As New MyFunctions()
            'If no Imports is used: As New SomeOtherNamespace.MyFunctions()
        End Sub
    End Class
End Namespace
Namespace SomeOtherNamespace
    Public Class MyFunctions
    End Class
End Namespace

如果两个类位于同一命名空间中,则示例:

Public Class MyFunctions
    Public Sub SomeMethod()
        'No need for Imports because they are in the same Namespace.
        Dim objMyFunctions As New MyFunctions()
    End Sub 
End Class
Public Class MyFunctions
End Class

最新更新