在 Visual Basic 中,变量将表示存储位置,每个变量将具有特定的数据类型,以确定变量可以保存的值类型。
Visual Basic 是一种强类型编程语言。在对变量执行任何作之前,必须使用所需的数据类型定义变量,以指示变量可以在应用程序中保存的数据类型。
1. 什么是变量
变量 =「可变的盒子」,有名字、有类型、有值,存在内存里。
VB 是强类型语言,先声明后使用(除非开启 Option Strict Off + Option Explicit Off,不推荐)。
Visual Basic 变量示例
下面是在 Visual Basic 中使用变量的示例。
Module Module1
Sub Main()
Dim id As Integer
Dim name As String = "Suresh Dasari"
Dim percentage As Double = 10.23
Dim gender As Char = "M"c
Dim isVerified As Boolean
id = 10
isVerified = True
Console.WriteLine("Id:{0}", id)
Console.WriteLine("Name:{0}", name)
Console.WriteLine("Percentage:{0}", percentage)
Console.WriteLine("Gender:{0}", gender)
Console.WriteLine("Verfied:{0}", isVerified)
Console.ReadLine()
End Sub
End Module
上面的例子表明,我们定义了多个具有不同数据类型的变量,并根据我们的要求分配了值。
当我们执行上面的例子时,我们将得到如下所示的结果。
Id:10
Name:Suresh Dasari
Percentage:10.23
Gender:M
Verfied:True
这就是我们如何根据我们的要求在 Visual Basic 应用程序中声明和初始化变量。
2. 声明语法(3 种)
写法
说明
示例
Dim
过程/模块级通用
Dim age As Integer = 18
Private
模块/类内部私有
Private counter As Long
Const
常量,运行期不可改
Const PI As Double = 3.1415926
Dim [Variable Name] As [Data Type]
Dim [Variable Name] As [Data Type] = [Value]
新版支持一次多变量:
Dim x, y As Integer ' x 被推断为 Integer
Dim name As String = "VB", price As Decimal = 9.9D
3. 命名规则
必须以字母或下划线开头,不能用数字或空格
只能含字母、数字、下划线(汉字也行,但别用)
大小写不敏感:name 与 NAME 是同一个变量
禁止系统关键字:If、Integer、End 等
见名知义:用 CamelCase 或下划线均可,统一即可
✅ 推荐
Dim totalScore As Integer
Dim _count As Long
❌ 错误
Dim 2ndName As String ' 数字开头
Dim End As Boolean ' 关键字冲突
4. 作用域与生命周期
声明位置
关键字
作用域
生命周期
过程内部
Dim
当前过程
过程结束即释放
模块/类级
Private
当前模块/类
程序结束才释放
全局
Public
整个项目
程序结束才释放
静态过程级
Static
当前过程
程序结束才释放,但值保持
Static 示例:统计按钮被点击次数
Private Sub btnCount_Click(sender As Object, e As EventArgs) Handles btnCount.Click
Static cnt As Integer = 0 ' 只初始化 1 次
cnt += 1
MessageBox.Show($"已点击 {cnt} 次")
End Sub
5. 类型推断 + 初始化
只要打开 Option Infer On(默认开启),就可让编译器自动推断:
Dim price = 9.9 ' 推断为 Double
Dim flag = True ' 推断为 Boolean
Dim today = #2025-09-29# ' 推断为 Date
注意:
① 必须同时赋初值,否则编译错误
② 推断后类型不可变:price = "abc" 会报错
6. 只读变量(ReadOnly)
Const 要求编译期就能算出值,不能用函数;
ReadOnly 允许运行期赋值,只能赋一次:
Public Class Config
Public ReadOnly StartTime As Date
Sub New()
StartTime = Date.Now ' 构造函数里可改
End Sub
End Class
7. 实战 1:控制台「年龄计算器」
Module AgeCalc
Sub Main()
Const CURRENT_YEAR As Integer = 2025
Console.Write("请输入出生年份:")
Dim birth As Integer
If Not Integer.TryParse(Console.ReadLine(), birth) Then
Console.WriteLine("输入不是整数!")
Return
End If
Dim age As Integer = CURRENT_YEAR - birth
Console.WriteLine($"到 {CURRENT_YEAR} 年,你的年龄是 {age} 岁")
Console.ReadKey()
End Sub
End Module
运行示例:
请输入出生年份:2005
到 2025 年,你的年龄是 20 岁
8. 小结口诀
变量先声明,类型要写清;
过程 Dim 临时的,模块 Private 长寿命;
常量用 Const,运行不改 ReadOnly;
命名见意思,下划线 Camel 随你意!