ValueType转BigInteger抛出InvalidCastException异常的解决方案
异常原因
这不是.NET框架的Bug,属于对C#拆箱转换规则的理解偏差:
- 所有值类型装箱为
object或ValueType类型存储后,执行强制类型转换时,必须先拆箱为其原始存储的值类型,无法一步同时完成「拆箱+跨自定义类型转换」两个操作。 - 示例中传入的
19是int类型,装箱后存储在ValueType类型的参数中,直接写(BigInteger)value1时,编译器无法在编译期识别参数的实际存储类型,只会生成拆箱为BigInteger的IL指令,不会自动插入int到BigInteger的转换逻辑;运行时尝试把存了int的装箱对象拆成BigInteger,自然会抛出System.InvalidCastException异常,和你查看IL得到的结论一致。
复现场景
参考官方ValueType类文档示例编写如下代码,传入普通整数参数时就会触发上述异常:
// 尝试用BigInteger作为统一整数比较类型 if (IsInteger(value1) && IsInteger(value2)) { BigInteger bigint1 = (BigInteger) value1; // 此处抛出System.InvalidCastException BigInteger bigint2 = (BigInteger) value2; // 此处抛出System.InvalidCastException return (NumericRelationship) BigInteger.Compare(bigint1, bigint2); }
触发异常的测试入口代码:
public class Example { public static void Main() { Console.WriteLine("{0} {1} {2}", 19, Utility.Compare(19, 19), 19); } }
正确转换方法
你测试通过的逐类型判断方案逻辑是正确的:先把装箱值拆箱为原始整数类型,再调用BigInteger对应构造函数完成转换,只是写法比较繁琐。可以利用所有基础数值类型都实现IConvertible接口的特性简化实现,不需要逐个枚举所有整数类型:
using System.Globalization; using System.Numerics; public static BigInteger ConvertToBigInteger(ValueType value) { // 本身就是BigInteger类型直接返回 if (value is BigInteger bigInt) return bigInt; // 内置整数类型统一通过IConvertible转Int64后构造BigInteger,避免逐类型判断 if (value is IConvertible convertible) return new BigInteger(convertible.ToInt64(CultureInfo.InvariantCulture)); // 兼容自定义实现了到BigInteger类型转换的场景 return (BigInteger)Convert.ChangeType(value, typeof(BigInteger), CultureInfo.InvariantCulture); }
提示:如果业务场景需要处理超过
Int64取值范围的超大整数,可以调整转换逻辑,增加对UInt64、Decimal类型的中转判断,避免转换溢出。
内容的提问来源于stack exchange,提问作者Aristos
相关产品推荐
相关产品推荐

