c# - 如何将`null`转换为可为空的int?我总是得到 0
问题描述
由于我不会让您感到厌烦的原因,我有一个值为 的通用对象null
,我需要将其转换为可为空的 int。
object foo = null
int? bar = Convert.ToInt32(foo) // bar = 0
int? bar = (int?)Convert.ToInt32(foo) // bar = 0
int? bar = Convert.ToInt32?(foo) // not a thing
从这个线程:
int? bar = Expression.Constant(foo, typeof(int?)); // Can not convert System.Linq.Expression.Constant to int?
我bar
需要null
。我该怎么做呢?
解决方案
以下将起作用
int? bar = (int?)foo;
但是,正如评论中指出的那样,如果不是 a或 an ,这将引发Specified cast is not valid
异常。foo
null
int
如果您只想获得一个null
如果转换无效,那么您可以使用
int? bar = foo as int?;
这将隐藏转换问题。
推荐阅读
- flutter - .document() 似乎不适用于我的颤动代码的特定部分
- design-patterns - 在 Rust 中,当你需要一个引用持有结构来有时拥有它的引用数据时,模式是什么?
- hyperledger-fabric - 超级账本结构,无法通过 docker 启动 orderer
- docker - 已经使用 docker 限制,为什么服务器 cpu 平均负载仍然很高
- javascript - “无法对未安装的组件执行 React 状态更新”错误
- java - MySQL TestContainers init-script 模式创建失败
- mysql - 为什么在插入过程中发生重复键错误时设置共享锁
- javascript - 简单的 PurgeCSS
- c - C - 单独的链式哈希表 - 输出和空间问题
- javascript - 连续显示两个 Div 列,这样它也可以与 AMP(加速移动页面)一起使用