C# 如何将'null'转换为可为null的int?我总是得到0分
出于不让您感到厌烦的原因,我有一个值为C# 如何将'null'转换为可为null的int?我总是得到0分,c#,asp.net,.net,C#,Asp.net,.net,出于不让您感到厌烦的原因,我有一个值为null的泛型对象,需要将其转换为可为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 发件人: 我需要bar为null。我该如何做到这一点?以下操作将起作用 int?bar=
null
的泛型对象,需要将其转换为可为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
发件人:
我需要
bar
为null
。我该如何做到这一点?以下操作将起作用
int?bar=(int?)foo代码>
但是,正如注释中指出的,如果foo
不是null
或int
的话,这将抛出一个指定强制转换无效的异常
如果您希望仅获取一个null
,如果转换无效,则可以使用
int?bar=foo作为int代码>
这将隐藏转换问题。int?bar=(int?)foo
似乎对我有用。Convert.ToInt32()
总是返回int
,而不是null
。这似乎是你最初尝试的主要缺陷。如果你去一棵苹果树,你总会得到一个苹果,而不是一个橘子。我个人建议int?bar=foo作为int
这比使用(int?
)稍微安全一点。可能的复制比我快几秒钟。伟大的头脑都是一样的!还是傻瓜们很少有不同意见:我觉得自己很傻。试图让事情变得比他们需要的更困难,我猜,等等……:)如果foo是字符串呢?它的类型为对象
,因此它没有义务转换为int?
。如果foo
不是null
或int
,肯定会出现运行时错误。。。但是所有的问题都需要将对象null
转换为int?空
。
int? bar = Expression.Constant(foo, typeof(int?)); // Can not convert System.Linq.Expression.Constant to int?