cv.cm

编码 · 编程语言

Visual Basic .NET 入门教程

阅读约 9 分钟

简短回答

Visual Basic .NET(VB.NET)是面向 .NET 平台的面向对象静态类型语言,关键字接近英语,如 Dim、If ... Then ... End If 和 For ... Next。它不区分大小写,使用与 C# 相同的 .NET 库。用 dotnet new console -lang VB 创建项目,用 dotnet run 运行。VBA 是 Microsoft Office 内的宏语言,是语法相似的老亲戚。

Visual Basic .NET 是什么,谁在用

VB.NET 是经典 Visual Basic(VB6)在 .NET 上的继任者。它与 C# 编译成同样的中间语言,所以两种语言可以共享库,甚至混合在同一个解决方案中。它主要用于 Windows 桌面应用程序(Windows Forms、WPF)、企业内部工具、ASP.NET Web 应用程序,以及现有 VB 代码库的维护。

微软继续在现代 .NET 上支持 Visual Basic,但已表示不打算再为这门语言增加重大的新特性;新的 .NET 功能通常先出现在 C# 中。对于没有现成 VB 代码的新项目,C# 是更常见的选择,但 VB.NET 对于学习编程和开发商业软件来说仍是一门易读的语言。

安装并运行 Hello, world

安装 .NET SDK(Windows、macOS 或 Linux)。Windows 上的 Visual Studio 还包含 Visual Basic 模板和可视化窗体设计器。

dotnet new console -lang VB -o HelloVB
cd HelloVB
dotnet run
# Hello, world!
' Program.vb
Imports System

Module Program
    Sub Main(args As String())
        Console.WriteLine("Hello, world!")
    End Sub
End Module

Module 存放共享过程,Sub Main 是入口点。注释以撇号 ' 开头。每条语句通常在行尾结束;没有分号和花括号。

变量与基本类型

用 Dim name As Type 声明变量。在 Option Infer On(默认)下,赋值时可以省略类型。在每个文件顶部写上 Option Strict On(或在项目中设置),这样有风险的隐式转换就会变成编译错误。

类型示例说明
IntegerDim n As Integer = 4232 位;Long 是 64 位
DoubleDim x As Double = 3.1464 位浮点数
DecimalDim price As Decimal = 19.99D精确的十进制数,适合表示金额
StringDim s As String = "hello"用 & 连接字符串
CharDim c As Char = "a"c单个字符,后缀 c
BooleanDim ok As Boolean = TrueTrue / False
DateDim d As Date = #2026-01-15#日期和时间值
Option Strict On
Module Types
    Sub Main()
        Dim name As String = "Ana"
        Dim age = 30                  ' inferred as Integer
        Console.WriteLine(name & " is " & age.ToString())
        Console.WriteLine($"Next year {name} is {age + 1}")
        Console.WriteLine(7 / 2)      ' 3.5 (always Double)
        Console.WriteLine(7 \ 2)      ' 3 (integer division)
        Console.WriteLine(7 Mod 2)    ' 1
    End Sub
End Module

控制流

Dim score = 85
If score >= 90 Then
    Console.WriteLine("A")
ElseIf score >= 80 Then
    Console.WriteLine("B")
Else
    Console.WriteLine("C")
End If

Select Case score
    Case 90 To 100
        Console.WriteLine("excellent")
    Case 80 To 89
        Console.WriteLine("good")
    Case Else
        Console.WriteLine("keep going")
End Select

For i = 1 To 3
    Console.WriteLine($"{i} squared is {i * i}")
Next

Dim n = 3
Do While n > 0
    n -= 1
Loop

这些语句要放在 Sub 内。For i = 1 To 3 包含两端;加上 Step -1 可倒着数。For Each item In collection 遍历任意集合。用 Exit For 或 Exit Do 提前离开循环。写条件时,优先使用 AndAlso 和 OrElse:一旦结果确定就停止求值,而 And 和 Or 总是对两边都求值。

Sub、函数与 Lambda

Sub 不返回值,Function 返回值。参数默认按 ByVal(副本)传递;ByRef 让过程可以改变调用者的变量。参数可以是带默认值的 Optional。

Function Add(a As Integer, b As Integer) As Integer
    Return a + b
End Function

Sub Greet(Optional name As String = "world")
    Console.WriteLine($"Hello, {name}!")
End Sub

Sub Increment(ByRef value As Integer)
    value += 1
End Sub

' Inside Sub Main:
Dim x = 5
Increment(x)                                  ' x is now 6
Greet()                                       ' Hello, world!
Dim square = Function(n As Integer) n * n     ' lambda
Console.WriteLine(square(Add(1, 2)))          ' 9

数组、List 与 Dictionary

Dim nums() As Integer = {3, 1, 2}
Dim five(4) As Integer            ' 5 elements, indexes 0 to 4
Array.Sort(nums)
Console.WriteLine(String.Join(", ", nums))   ' 1, 2, 3

Dim names As New List(Of String) From {"Ana", "Ben"}
names.Add("Cleo")
Console.WriteLine(names.Count)               ' 3

Dim ages As New Dictionary(Of String, Integer)
ages("Ana") = 30
ages("Ben") = 17
For Each pair In ages
    Console.WriteLine($"{pair.Key}: {pair.Value}")
Next

数组和列表用括号从 0 开始索引:nums(0)。泛型类型使用 Of:List(Of String) 是 C# 中 List<string> 的 VB 写法。注意 Dim five(4) 声明的是上界,而不是长度,所以数组有五个元素。

标志性特性:类、属性与 LINQ 查询

VB.NET 完全面向对象:类有属性、方法、构造函数(Sub New)、继承(Inherits)、接口(Implements)和事件(Event、RaiseEvent、Handles)。LINQ 查询可以用易读的查询语法书写。

Public Class Person
    Public Property Name As String
    Public Property Age As Integer

    Public Sub New(name As String, age As Integer)
        Me.Name = name
        Me.Age = age
    End Sub
End Class

' Inside Sub Main:
Dim people As New List(Of Person) From {
    New Person("Ana", 30),
    New Person("Ben", 17)
}
Dim adults = From p In people
             Where p.Age >= 18
             Select p.Name
For Each adultName In adults
    Console.WriteLine(adultName)   ' Ana
Next

由于 VB 不区分大小写,Name 和 name 是同一个标识符;在构造函数内,Me.Name 指属性,name 指参数。其他 VB 特有的便利功能包括 With ... End With 块、XML 字面量,以及用于常见任务的 My 命名空间。

错误处理

VB.NET 使用结构化异常处理:Try、Catch、Finally 和 Throw。Catch 可以带 When 过滤器。VB6 和 VBA 中较老的 On Error GoTo 风格仍然可以编译,但不应在新的 .NET 代码中使用。

Function ParseAge(s As String) As Integer
    Dim n As Integer
    If Not Integer.TryParse(s, n) Then
        Throw New FormatException($"Not a number: {s}")
    End If
    If n < 0 Then Throw New ArgumentOutOfRangeException(NameOf(s))
    Return n
End Function

' Inside Sub Main:
Try
    Console.WriteLine(ParseAge("abc"))
Catch ex As FormatException
    Console.WriteLine("Error: " & ex.Message)   ' Error: Not a number: abc
Finally
    Console.WriteLine("done")
End Try

一个完整的小程序:词频统计

Imports System
Imports System.Collections.Generic
Imports System.Linq

Module WordCount
    Sub Main()
        Dim text = "the cat and the hat and the bat"
        Dim counts As New Dictionary(Of String, Integer)

        For Each word In text.Split(" "c)
            If counts.ContainsKey(word) Then
                counts(word) += 1
            Else
                counts(word) = 1
            End If
        Next

        Dim top = counts.OrderByDescending(Function(kv) kv.Value).Take(2)
        For Each kv In top
            Console.WriteLine($"{kv.Key} {kv.Value}")
        Next
    End Sub
End Module
' the 3
' and 2

VBA:Microsoft Office 里的 Visual Basic

Visual Basic for Applications(VBA)是内置于 Excel、Word 和 Access 等 Microsoft Office 应用程序的宏语言。它基于经典 Visual Basic,而不是 .NET:它运行在 Office 应用程序内部,使用 Office 对象模型(工作簿、单元格区域、文档),并在 VBA 编辑器中编辑(Windows 上按 Alt+F11)。Dim、If、For 和 Sub 的基本语法相同,所以掌握 VB.NET 对学 VBA 很有用。

' VBA in Excel: write the squares of 1 to 5 into column A
Sub FillSquares()
    Dim i As Long
    For i = 1 To 5
        Cells(i, 1).Value = i * i
    Next i
    MsgBox "Done"
End Sub

接下来读什么

  • Microsoft Learn:Visual Basic 文档,包括入门指南和语言参考。
  • 学习 .NET 基类库(集合、文件、LINQ);它与 C# 共用。
  • 做桌面应用,可以在 Visual Studio 中试试 Windows Forms 或 WPF 模板。
  • 做 Office 自动化,请阅读 Microsoft Learn 上你所用应用程序的 VBA 参考。

常见问题

Visual Basic .NET 已经死了吗?

没有。当前的 .NET 版本和 Visual Studio 都支持它,但微软不打算增加重大的新语言特性,所以大多数新的 .NET 项目选择 C#。

VB.NET 和 VBA 有什么区别?

VB.NET 是完整的 .NET 语言,用于构建独立应用程序。VBA 是基于经典 Visual Basic 的宏语言,运行在 Excel 等 Office 应用程序内部;两者语法相似,但运行时和库不同。

应该学 VB.NET 还是 C#?

如果你要维护 VB 代码,或想要非常易读的语法,VB.NET 就可以。对于新项目、就业机会和最新的 .NET 功能,C# 通常是更值得的投入,而且你学到的库在两者之间是通用的。

Visual Basic 区分大小写吗?

不区分。Dim Total、total 和 TOTAL 指的是同一个变量,编辑器通常会替你统一大小写。

全部编码教程