VB.NET 命名空间和类语法

标签 vb.net class syntax visual-studio-2005 namespaces

我在下面的代码中缺少什么?也许是范围问题?语法问题?

我添加了一个新文件,class1.vb , 到我的 VB.NET 项目,其中包含:

Namespace MyFunc1
    Public Class MyFunc2

        Public Function Add(ByVal n1 As Int16, ByVal n2 As Int16) As Int16
            return n1 + n2  ' Edited from: "Add = n1 + n2" (same thing)
        End Function

    End Class
End Namespace

回到我的 form1.vb 这靠近顶部:
Imports MyCode.MyFunc1  ' A handful of generic functions

在 form1.vb 中,我以为我曾经能够使用以下命令调用我的函数:
n = MyFunc1.Add(15, 16)

错误提示“它不是成员(member)”。
这些也不能按预期工作:
n = MyFunc2.Add(15, 16)
n = MyFunc1.MyFunc2.Add(15, 16)
n = Add(15, 16)

我确信,这曾经奏效:
n = MyFunc1.Add(15, 16)

最佳答案

为了以您想要的方式执行此操作,您需要按照@Chipmunk 的建议创建类的实例,或者将方法设为 Shared。您还应该摆脱执行此操作的旧 VB6 方法。您的方法应如下所示:

Public Shared Function Add(ByVal n1 As Int16, ByVal n2 As Int16) As Int16
    Return n1 + n2
End Function

编辑:
然后将使用以下方法调用它:
Dim x as Int16 = MyFunc1.MyFunc2.Add(15, 16)

使用 Call假设您正在执行一个子程序而不是一个函数。函数的目的是返回数据。简单 Call ing 它不会产生预期的效果。

编辑 2(示例)

您可以为此使用模块,如@Chipmunk 所述,也可以使用类。我的偏好只是类,因为 MS 还没有对模块下定决心(他们在其中一个版本中取消了它们 - 我忘记了 - 然后将它们带回来)。

类方法
Namespace MyFunc1
    Public Class MyFunc2

        Public Shared Function Add(ByVal n1 As Int16, ByVal n2 As Int16) As Int16
            Return n1 + n2    
        End Function

    End Class
End Namespace

Form1.vb 中的用法
Imports MyFunc1

...

Public Sub DoAdd()
    Dim x as Int16 = MyFunc2.Add(15, 16)  ' MyFunc1 Namespace imported, MyFunc2
                                          ' is assumed. No instance is created
End Sub

模块方法
Public Module MyFunctions

    ' Notice no shared modifier here. The module uses the legacy module
    ' concept to assume that it is shared
    Public Function Add(ByVal n1 as Int16, ByVal n2 as Int16) As Int16
        Return n1 + n2
    End Function

End Module

Form1.vb 中的用法

由于模块将位于项目中的引用命名空间中,因此您只需直接调用它:
Public Sub DoAdd()
    Dim x as Int16 = MyFunctions.Add(15, 16)  ' This assumes that your MyFunctions
                                              ' module is in an imported namespace
End Sub

关于VB.NET 命名空间和类语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5582829/

相关文章:

php - 通过 JOIN 在单个查询中查询多个表

c# - 匿名实例化语法——好还是坏?

syntax - 如何使用依赖于实体的其他泛型参数的泛型参数?

vb.net - Jenkins 抛出未知的汇编错误

vb.net - 如何在 VB.NET 中单击按钮切换表单语言?

.net - 更改文本框输入

jquery - 如何在两个表行之间插入另一个表行?

php - "Magic""class"

.net - 错误解析引用

Java : ClassNotFoundException when running program with netty [Gradle]