症状
强制转换抛出 InvalidCastException: Unable to cast object of type 'X' to type 'Y'。它常只在特定输入下出现,例如预期 long 却传入装箱的 int。
诊断
注意消息中的两个类型并检查该值:
object boxed = 42; // boxed int
long l = (long)boxed; // InvalidCastException
装箱的值类型必须按精确类型拆箱。
修复
使用模式匹配与正确的数值转换:
if (obj is string s) {
Handle(s);
}
object boxed = 42;
long l = Convert.ToInt64(boxed); // correct numeric conversion
尽量以泛型替代 object 集合。
验证
用出问题的值重跑;模式分支或转换成功。补测试覆盖类型匹配与不匹配两条路径。