"""Offline ASP.NET Razor C# variables verification lab for Chapter 20 (razor-cs-variables)."""
from datetime import date, datetime
from decimal import Decimal, InvalidOperation
import json
import re
VERSION = "CPython 3.12.14 offline ASP.NET Razor C# variables semantic verifier (IIS/ASP.NET host absent)"
def case_var_and_explicit_type_declarations():
cs_keywords = {"int", "string", "var", "if", "else", "for", "return", "class", "bool"}
def is_valid_cs_identifier(name):
return bool(re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name)) and name not in cs_keywords
inferred = {
"greeting": ("string", "Welcome to ASP.NET"),
"counter": ("int", 103),
"today": ("DateTime", date(2026, 11, 2).isoformat()),
}
explicit = {
"greeting": ("string", "Welcome to ASP.NET"),
"counter": ("int", 103),
"today": ("DateTime", date(2026, 11, 2).isoformat()),
}
expected = {
"valid_names": [True, True, False, False, False],
"var_equals_explicit": True,
"counter_type": "int",
}
actual = {
"valid_names": [
is_valid_cs_identifier("greeting"),
is_valid_cs_identifier("_totalCount"),
is_valid_cs_identifier("2ndValue"),
is_valid_cs_identifier("my var"),
is_valid_cs_identifier("class"),
],
"var_equals_explicit": inferred == explicit,
"counter_type": inferred["counter"][0],
}
return {
"name": "var_and_explicit_type_declarations",
"summary": "校验 C# 标识符命名规则、var 编译期类型推断与显式类型声明(string/int/DateTime)等价性",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_cs_primitive_types_and_literals():
samples = {
"int": [103, 12, 5168],
"float": [3.14, 3.4e38],
"decimal": Decimal("1037.196543"),
"bool": [True, False],
"string": ["Hello BlueSky", "John"],
}
decimal_sum = Decimal("0.1") + Decimal("0.2")
float_sum_exact = (0.1 + 0.2) == 0.3
expected = {
"int_count": 3,
"float_scientific_gt_1e30": True,
"decimal_str": "1037.196543",
"decimal_exact_0_3": True,
"binary_float_exact_0_3": False,
"bool_values": [True, False],
"string_joined": "Hello BlueSky, John",
}
actual = {
"int_count": len(samples["int"]),
"float_scientific_gt_1e30": samples["float"][1] > 1e30,
"decimal_str": str(samples["decimal"]),
"decimal_exact_0_3": decimal_sum == Decimal("0.3"),
"binary_float_exact_0_3": float_sum_exact,
"bool_values": samples["bool"],
"string_joined": ", ".join(samples["string"]),
}
return {
"name": "cs_primitive_types_and_literals",
"summary": "验证 C# 常用数据类型(int/float/decimal/bool/string)与高精度十进制 decimal 精度差异",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_cs_operators_and_precedence():
i = 6
arith = [5 + 5, 5 - 5, 5 * 5, 5 // 5]
i += 1
inc_val = i
i -= 1
dec_val = i
names = ["Ada", "Bob", "Cid", "Dan"]
ready, clear = True, False
add_fn = lambda a, b: a + b
expected = {
"arith": [10, 0, 25, 1],
"inc_dec": [7, 6],
"eq_neq": [False, True],
"rel": [True, False, True, False],
"concat": "ASP.NET",
"grouped_and_call": [11, 11],
"indexed": "Dan",
"logic": [False, False, True],
}
actual = {
"arith": arith,
"inc_dec": [inc_val, dec_val],
"eq_neq": [i == 10, i != 10],
"rel": [i < 10, i > 10, i <= 10, i >= 10],
"concat": "ASP" + ".NET",
"grouped_and_call": [(i + 5), add_fn(i, 5)],
"indexed": names[3],
"logic": [not ready, ready and clear, ready or clear],
}
return {
"name": "cs_operators_and_precedence",
"summary": "逐项核验 C# 赋值、算术、自增减、比较、字符串连接、索引 []、分组调用 () 与逻辑运算符",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_string_type_conversion_helpers():
def is_int(s):
return bool(re.fullmatch(r"[+-]?\d+", s.strip()))
def as_int(s, default=0):
return int(s.strip()) if is_int(s) else default
def is_float(s):
try:
float(s.strip())
return True
except ValueError:
return False
def as_float(s, default=0.0):
return float(s.strip()) if is_float(s) else default
def is_decimal(s):
try:
Decimal(s.strip())
return True
except InvalidOperation:
return False
def as_decimal(s, default=Decimal("0")):
return Decimal(s.strip()) if is_decimal(s) else default
def is_datetime(s):
try:
datetime.strptime(s.strip(), "%m/%d/%Y")
return True
except ValueError:
return False
def as_datetime(s):
return datetime.strptime(s.strip(), "%m/%d/%Y").strftime("%Y-%m-%d")
def is_bool(s):
return s.strip().lower() in {"true", "false"}
def as_bool(s, default=False):
low = s.strip().lower()
return True if low == "true" else (False if low == "false" else default)
expected = {
"int_ok": [True, 2048],
"int_bad": [False, 0],
"float_ok": [True, 3.14],
"decimal_ok": [True, "1037.196543"],
"date_ok": [True, "2012-10-10"],
"bool_ok": [True, True],
"to_string": "1234",
}
actual = {
"int_ok": [is_int("2048"), as_int("2048")],
"int_bad": [is_int("12a"), as_int("12a")],
"float_ok": [is_float("3.14"), as_float("3.14")],
"decimal_ok": [is_decimal("1037.196543"), str(as_decimal("1037.196543"))],
"date_ok": [is_datetime("10/10/2012"), as_datetime("10/10/2012")],
"bool_ok": [is_bool("True"), as_bool("True")],
"to_string": str(1234),
}
return {
"name": "string_type_conversion_helpers",
"summary": "模拟 Razor Web Pages 的 IsInt/AsInt、IsFloat/AsFloat、IsDecimal/AsDecimal、IsDateTime/AsDateTime、IsBool/AsBool 与 ToString",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_var_and_explicit_type_declarations(),
case_cs_primitive_types_and_literals(),
case_cs_operators_and_precedence(),
case_string_type_conversion_helpers(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 ASP.NET Razor / MVC 语义验证器(未启动 Visual Studio / IIS / ASP.NET MVC 运行时宿主)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 ASP.NET Razor / MVC 语义验证器(未启动 Visual Studio / IIS / ASP.NET MVC 运行时宿主)。
入口文件:projects/razor-cs-variables-lab/explore-cs-variables.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-cs-variables.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 ASP.NET Razor / MVC 语义验证器(未启动 Visual Studio / IIS / ASP.NET MVC 运行时宿主)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联55章) · 含当前章节或实例 · mbskycom202612a2925.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2928.zip