c# - 拆箱到更大的值类型

标签 c# .net boxing unboxing

以下代码导致 InvalidCastException

  object x = (short) 1;
  int y = (int) x;

我知道我可以先将 x 转换为 short,然后再转换为 int,尽管这不是一个选项,因为装箱值的类型未知(但它肯定小于 int)。

当拆箱到大于装箱类型的类型时,如何解决异常?

编辑: 我通过使用 dynamic 类型解决了我的问题(具有所有性能影响)

最佳答案

您可以 only unbox an object to its exact type .

相反,您应该调用 Convert.ToInt32(),它适用于任何数字类型。

关于c# - 拆箱到更大的值类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13503693/

相关文章:

c# - 我的问题是关于使用 C# linq 比较 List<string> 与 Dictionary <string, List<string>>

c# - 如何禁用对用于验证消息签名的 x509 证书的验证?

c# - 如何在 C# 中获取 string[] 数组的一部分

c# - 多个消费者和查询 C# BlockingCollection

c# - 在 View 模型中实现 IDataErrorInfo

c# - 将 Func<T, int> 值插入 linq-2-sql 查询

c# - 为什么 ItemsSource 不绑定(bind)到我的自定义 CollectionChanged 事件

c# - 为什么我不能修改拆箱转换的结果?

c# - 从 Dictionary<string, object> 中获取值而不拆箱?

c# - 在 C# 中使用接口(interface)时的值与引用类型