首页 > 解决方案 > 如何将`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。我该怎么做呢?

标签: c#asp.net.net

解决方案


以下将起作用

int? bar = (int?)foo;

但是,正如评论中指出的那样,如果不是 a或 an ,这将引发Specified cast is not valid异常。foonullint

如果您只想获得一个null如果转换无效,那么您可以使用

int? bar = foo as int?;

这将隐藏转换问题。


推荐阅读