Razor VB 变量
系统梳理传统 ASP.NET Razor VB(.vbhtml)的 Dim/As 变量声明、常用数据类型、算术/比较/短路运算符(AndAlso/OrElse)与类型转换方法,并纠正常见注释与运算符细节。
学完这一章,你能够
- 系统梳理传统 ASP.NET Razor VB(.vbhtml)的 Dim/As 变量声明、常用数据类型、算术/比较/短路运算符(AndAlso/OrElse)与类型转换方法,并纠正常见注释与运算符细节。
VB 变量命名规则与 Dim / As 声明
在 Razor VB(`.vbhtml`)中,变量同样是存储数据的命名实体,名称须以字母或下划线开头且不得包含空格或保留字,但 VB 标识符不区分大小写。声明局部变量使用 `Dim` 关键字:开启局部类型推断(`Option Infer On`)时可直接写 `Dim greeting = "Welcome to ASP.NET"`、`Dim counter = 103`、`Dim today = DateTime.Today`,也可显式通过 `As` 指定类型(`Dim greeting As String`、`Dim counter As Integer`、`Dim today As DateTime`)。需特别提醒:VB 的单行注释符号是单引号 `'`(而非 C# 的 `//`),且 ASP.NET Core 已停止支持 `.vbhtml`,新开发推荐选用 C# `.cshtml`。
VB 常用数据类型与运算符体系
Razor VB 常用基础类型包括 32 位整数 `Integer`、64 位双精度浮点 `Double`、高精度十进制 `Decimal`、布尔 `Boolean` 与文本 `String`(详见下表,因 VB 不区分大小写,源码中常见小写或帕斯卡拼写)。
VB 运算符体系在若干关键符号上与 C# 不同(详见下表):`=` 既作赋值也作相等比较;不等号写为 `<>`(例如 `If i <> 10`);字符串拼接推荐使用 `&`;数组与集合下标使用圆括号 `name(3)` 而非方括号;逻辑运算除普通按位/急切求值的 `And`、`Or` 外,还提供短路求值的 `AndAlso` 与 `OrElse`(当左侧已能决定结果时跳过右侧求值,避免空引用异常)。
用户输入字符串的类型转换方法
与 C# 页面一样,HTTP 表单输入到达服务器时均为字符串,在用于算术或日期计算前必须完成类型转换。在传统 ASP.NET Web Pages 中,VB 同样调用 `IsInt()/AsInt()`、`IsFloat()/AsFloat()`、`IsDecimal()/AsDecimal()`、`IsDateTime()/AsDateTime()`、`IsBool()/AsBool()` 以及通用 `ToString()`(详见下表);若编写标准 .NET 代码则对应使用 `Integer.TryParse`、`Decimal.TryParse`、`DateTime.TryParse` 与 `Boolean.TryParse`。
Razor VB 常用基础数据类型速查
| 类型 | 说明与精度特性 | 典型字面量示例 |
| Integer | 32 位有符号整数(全数字)。 | 103, 12, 5168 |
| Double | 64 位双精度浮点数。 | 3.14, 3.4e38 |
| Decimal | 128 位高精度十进制数字,适合财务精确计算。 | 1037.196543D |
| Boolean | 布尔逻辑值,取值为 True 或 False。 | True, False |
| String | Unicode 字符串,使用双引号界定。 | "Hello BlueSky", "John" |
Razor VB 常用运算符速查
| 运算符 | 作用说明 | 表达式示例 |
| =(赋值) | 将右侧值赋给左侧变量。 | i = 6 |
| + - * / | 算术加、减、乘、除运算(/ 为浮点除,整数除使用 \)。 | i = 5 + 5 : i = 5 - 5 : i = 5 * 5 : i = 5 / 5 |
| += -= | 复合赋值,对变量执行递增或递减。 | i += 1 : i -= 1 |
| =(相等) | 在条件表达式中判断两侧值是否相等。 | If i = 10 Then |
| <> | 不等比较,两侧值不相等时返回 True。 | If i <> 10 Then |
| < > <= >= | 小于、大于、小于等于、大于等于关系比较。 | If i < 10 Then : If i >= 10 Then |
| & | 专用字符串连接运算符,避免与数值加法混淆。 | "ASP" & ".NET" |
| . | 点号成员访问符,分隔对象与其属性或方法(如 DateTime.Now.Hour)。 | DateTime.Now.Hour |
| ()(分组) | 圆括号用于表达式分组并提高计算优先级。 | (i + 5) |
| ()(传参) | 圆括号用于向函数或子过程传递实参。 | x = Add(i, 5) |
| ()(索引) | VB 中数组与集合元素访问同样使用圆括号而非方括号。 | name(3) |
| Not | 逻辑非,对布尔表达式取反。 | If Not ready Then |
| And Or | 急切求值逻辑与/或:无论左侧结果如何都会计算右侧表达式。 | If ready And clear Then : If ready Or clear Then |
| AndAlso OrElse | 短路逻辑与/或:左侧已决定真假时跳过右侧求值,工程中优先使用。 | If ready AndAlso clear Then : If ready OrElse clear Then |
Razor VB 常用数据类型转换方法
| 方法 | 转换用途说明 | VB 调用示例 |
| IsInt() / AsInt() | 校验并将字符串转为整数。 | If myString.IsInt() Then myInt = myString.AsInt() |
| IsFloat() / AsFloat() | 校验并将字符串转为单精度浮点数。 | If myString.IsFloat() Then myFloat = myString.AsFloat() |
| IsDecimal() / AsDecimal() | 校验并将字符串转为高精度十进制数。 | If myString.IsDecimal() Then myDec = myString.AsDecimal() |
| IsDateTime() / AsDateTime() | 将字符串解析为 ASP.NET DateTime 类型。 | myString = "10/10/2012" : myDate = myString.AsDateTime() |
| IsBool() / AsBool() | 将字符串转换为布尔值。 | myString = "True" : myBool = myString.AsBool() |
| ToString() | 将任意数据类型转换为字符串。 | myInt = 1234 : myString = myInt.ToString() |
离线校验 Razor VB Dim/As 声明、And 与 AndAlso 短路差异及类型转换
展开查看收起
"""Offline ASP.NET Razor VB variables verification lab for Chapter 23 (razor-vb-variables)."""
from datetime import date, datetime
from decimal import Decimal, InvalidOperation
import json
import re
VERSION = "CPython 3.12.14 offline ASP.NET Razor VB variables semantic verifier (IIS/ASP.NET host absent)"
def case_vb_dim_and_as_type_declarations():
decl_lines = [
'Dim greeting = "Welcome to ASP.NET"',
'Dim counter = 103',
'Dim today = DateTime.Today',
'Dim greeting2 As String = "Welcome to ASP.NET"',
'Dim counter2 As Integer = 103',
'Dim today2 As DateTime = DateTime.Today',
]
parsed = {}
for ln in decl_lines:
m = re.match(r'^Dim\s+([A-Za-z_]\w*)(?:\s+As\s+([A-Za-z]+))?\s*=\s*(.+)$', ln, flags=re.I)
assert m
name, explicit_type, expr = m.group(1).lower(), m.group(2), m.group(3)
if expr.startswith('"'):
inferred, val = "String", expr.strip('"')
elif expr.isdigit():
inferred, val = "Integer", int(expr)
else:
inferred, val = "DateTime", date(2026, 11, 2).isoformat()
parsed[name] = (explicit_type or inferred, val)
expected = {
"inferred_matches_explicit": True,
"comment_prefix_vb": "'",
"types": ["String", "Integer", "DateTime"],
}
actual = {
"inferred_matches_explicit": (
parsed["greeting"] == parsed["greeting2"]
and parsed["counter"] == parsed["counter2"]
and parsed["today"] == parsed["today2"]
),
"comment_prefix_vb": "'",
"types": [parsed["greeting"][0], parsed["counter"][0], parsed["today"][0]],
}
return {
"name": "vb_dim_and_as_type_declarations",
"summary": "解析 VB Dim 隐式推断与 Dim ... As Type 显式声明,并核对单引号 ' 注释语法规范",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_vb_types_and_case_insensitivity():
sym = {}
sym["mycount"] = 103
sym["ratio"] = 3.14
sym["amount"] = Decimal("1037.196543")
sym["isactive"] = True
sym["username"] = "John"
expected = {
"case_insensitive_hit": True,
"double_val": 3.14,
"decimal_str": "1037.196543",
"bool_val": True,
"string_val": "John",
}
actual = {
"case_insensitive_hit": sym["MYCOUNT".lower()] == 103 and sym["MyCount".lower()] == 103,
"double_val": sym["ratio"],
"decimal_str": str(sym["amount"]),
"bool_val": sym["isactive"],
"string_val": sym["username"],
}
return {
"name": "vb_types_and_case_insensitivity",
"summary": "核对 VB 常用数据类型(Integer/Double/Decimal/Boolean/String)与标识符不区分大小写特性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_vb_operators_and_short_circuit():
i = 6
arith = [5 + 5, 5 - 5, 5 * 5, 5 / 5]
i += 1
inc_v = i
i -= 1
dec_v = i
names = ["Ada", "Bob", "Cid", "Dan"]
eval_log = []
def rhs():
eval_log.append("rhs_evaluated")
return True
eager_and = (False & rhs())
eager_count = len(eval_log)
eval_log.clear()
short_and_also = (False and rhs())
short_count = len(eval_log)
expected = {
"arith": [10, 0, 25, 1.0],
"inc_dec": [7, 6],
"vb_eq_neq": [False, True],
"vb_concat": "ASP.NET",
"vb_array_parens": "Dan",
"eager_and_called_rhs": [False, 1],
"short_circuit_andalso_skipped_rhs": [False, 0],
}
actual = {
"arith": arith,
"inc_dec": [inc_v, dec_v],
"vb_eq_neq": [i == 10, i != 10],
"vb_concat": "ASP" + ".NET",
"vb_array_parens": names[3],
"eager_and_called_rhs": [bool(eager_and), eager_count],
"short_circuit_andalso_skipped_rhs": [bool(short_and_also), short_count],
}
return {
"name": "vb_operators_and_short_circuit",
"summary": "校验 VB =/=/<> 比较、& 字符串连接、() 数组索引,以及 And/Or 急切求值与 AndAlso/OrElse 短路求值差异",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_vb_string_conversion_helpers():
def is_int(s):
return bool(re.fullmatch(r"[+-]?\d+", s.strip()))
def as_int(s):
return int(s.strip()) if is_int(s) else 0
def is_float(s):
try:
float(s.strip())
return True
except ValueError:
return False
def is_decimal(s):
try:
Decimal(s.strip())
return True
except InvalidOperation:
return False
def as_datetime(s):
return datetime.strptime(s.strip(), "%m/%d/%Y").strftime("%Y-%m-%d")
def as_bool(s):
return s.strip().lower() == "true"
expected = {
"int_pair": [True, 42],
"float_pair": [True, 2.5],
"decimal_pair": [True, "99.95"],
"datetime_iso": "2012-10-10",
"bool_val": True,
"to_string": "1234",
}
actual = {
"int_pair": [is_int("42"), as_int("42")],
"float_pair": [is_float("2.5"), float("2.5")],
"decimal_pair": [is_decimal("99.95"), str(Decimal("99.95"))],
"datetime_iso": as_datetime("10/10/2012"),
"bool_val": as_bool("True"),
"to_string": str(1234),
}
return {
"name": "vb_string_conversion_helpers",
"summary": "模拟 Razor VB 中的 IsInt/AsInt、IsFloat/AsFloat、IsDecimal/AsDecimal、AsDateTime、AsBool 与 ToString",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_vb_dim_and_as_type_declarations(),
case_vb_types_and_case_insensitivity(),
case_vb_operators_and_short_circuit(),
case_vb_string_conversion_helpers(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`And` 是非短路运算符,即使 `obj` 为 `Nothing` 仍会继续求值右侧 `obj.Count > 0` 从而抛出 `NullReferenceException`;`AndAlso` 具备短路特性,左侧为假时立即停止,不会触发空引用异常。