Visual Basic (VB) 关键字大全

2025-09-29 16:50 更新

在 Visual Basic 中,关键字是预定义的保留字集,对编译器具有特殊含义。因此,Visual Basic 中的关键字不能在我们的应用程序中用作变量名、类名等标识符。

1. 什么是关键字

关键字 = 编译器保留的「专用词」,不能用作变量名、过程名、类名。
VB 不区分大小写,因此 If / IF / if 都视为同一个关键字。

Visual Basic 关键字类型

在 Visual Basic 中,关键字分为两种类型,即

  • 保留关键字
  • 未保留关键字

2. 分类速记表

类别 常用关键字(按字母序) 记忆口诀
控制流程 If, Then, Else, ElseIf, Select, Case, For, Next, For Each, While, End While, Do, Loop, Until, Exit, Continue, Return, GoTo 如果选循环,退出继续回
异常 Try, Catch, Finally, Throw, When 抓住最后抛
声明/作用域 Dim, Const, Static, ReadOnly, Private, Public, Friend, Protected, MustInherit, NotInheritable, Partial, Shadows, Overloads, Overrides, Overridable, NotOverridable, MustOverride, Shared, Module, Class, Structure, Interface, Enum, Namespace, Imports, Alias, Using, With, End With 公私友护,重载覆盖,共享枚举
运算符 And, AndAlso, Or, OrElse, Not, Xor, Is, IsNot, Like, Mod, AddressOf, GetType, TypeOf, In, Like 与或非模,地址类型
类型/转换 Boolean, Byte, SByte, Short, UShort, Integer, UInteger, Long, ULong, Decimal, Single, Double, Date, Char, String, Object, CType, DirectCast, TryCast, CBool, CByte, CInt, CLng, CDec, CSng, CDbl, CDate, CChar, CStr, CObj 基本类型,C 系列转换
参数/返回 Sub, Function, Property, Get, Set, ParamArray, Optional, ByVal, ByRef, Ref, In, Out, Yield, Async, Await, Handles, AddHandler, RemoveHandler, RaiseEvent 参可空,异步等
内存/资源 New, Nothing, Erase, ReDim, Preserve, Me, MyBase, MyClass, Global 新无重定义,我基类
编译指令 Option, Strict, Explicit, Compare, Infer, Assembly, Module 放在文件最顶部
LINQ From, Where, Select, Order By, Asc/Desc, Group, Join, Let, Distinct, Skip, Take, Aggregate, Into, On, Equals 查询语法糖
其他 Call, Case, Default, Each, Else, Error, Event, GetType, GoSub, Let, Lib, Loop, Name, Next, Of, Operator, Region, Rem, Resume, Step, Stop, Then, To, Until, When, While, WithEvents, Add, Remove, Iterator, Partial, Await 少见或历史兼容

完整官方列表:

https://learn.microsoft.com/zh-cn/dotnet/visual-basic/language-reference/keywords/

3. 实战:关键字冲突怎么办?

场景:想用 Date 做变量名 → 编译报错「关键字冲突」
解决:前后加方括号 [ ] 即可

Dim [Date] As Date = #2025-09-29#   ' 合法
Console.WriteLine([Date])

建议:尽量少用,代码可读性差。

4. 编译器指令关键字(文件级)

放在 最顶部,影响当前文件编译行为:

Option Strict On      ' 禁止隐式缩窄转换
Option Explicit On    ' 强制声明变量
Option Infer On       ' 允许 Dim 推断
Option Compare Text   ' 字符串比较忽略大小写

5. 上下文关键字(只在特定位置才认)

VB.NET 新增「上下文关键字」——不必方括号也能当标识符:
Ascending, Descending, Equals, Group, Join, Let, Order By, Partial, Select, Skip, Take, Value, Xml, Await, Async
示例:变量名与 LINQ 关键字不冲突

Dim Value As Integer = 10      ' 合法
Dim result = From v In New Integer() {1, 2, 3}
             Where v > Value
             Select v

6. 小结口诀

一百十九保留词,大小写无关要牢记;

命名冲突加括号,指令置顶严与宽;

上下文词看位置,可读优先少取巧!

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号