为什么Convert.ToInt32(空)在c#返回0 [英] Why Convert.ToInt32(null) returns 0 in c#

查看:804
本文介绍了为什么Convert.ToInt32(空)在c#返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是今天这个碰上了,如果你将null转换为INT32

  Convert.ToInt32(空)

则返回0



我期待一个InvalidCastException ..



任何想法,为什么出现这种情况?


解决方案

任何想法,为什么出现这种情况?




由于这是该记录的行为?无论是 Convert.ToInt32(对象) Convert.ToInt32(串) ,该文档指出很清楚:



(下返回值)




32位有符号整数,相当于值为0(零)如果值为null数量或







一个32位有符号整数等效值或零,如果值是空。




一如往常,如果现实不匹配的期望,你应该做的第一件事是检查你的期望是否匹配记录的行​​为。



我个人不完全买加文所示的说法与VB6的兼容性。我知道它来自微软,它可能是真正的原因,它的行为这样 - 但我不认为这是一个的的理由的行为是那样。有很多具体的VB-转换方法 - 因此,如果框架的设计者确实认为返回零是一个非理想的结果,他们应该做什么,他们认为最好的,和VB6程序员提供了一种用于VB6兼容的转换



显然,一旦行为是在.NET 1.0中定义,它不能被改变以后的版本 - 但是这并不等于说它必须的行为方式相同VB6


I just came across this today, if you convert null to int32

Convert.ToInt32(null)

it returns 0

I was expecting an InvalidCastException...

Any idea why this happen?

解决方案

Any idea why this happen?

Because that's the documented behaviour? Whether it's Convert.ToInt32(object) or Convert.ToInt32(string), the documentation states quite clearly:

(Under return value)

A 32-bit signed integer that is equivalent to the number in value, or 0 (zero) if value is null.

or

A 32-bit signed integer equivalent to value, or zero if value is null.

As always, if reality doesn't match expectations, the first thing you should do is check whether your expectations match the documented behaviour.

Personally I don't fully buy the "compatibility with VB6" argument shown by Gavin. I realize it comes from Microsoft, and it may well be the genuine reason why it behaves that way - but I don't think it's a good reason to behave that way. There are plenty of VB-specific conversion methods - so if the framework designers genuinely thought that returning zero was a non-ideal result, they should have done whatever they thought best, and provided a VB6 compatible conversion for use by VB6 programmers.

Obviously once the behavior was defined in .NET 1.0, it couldn't be changed for later versions - but that's not the same as saying it had to behave the same way as VB6.

这篇关于为什么Convert.ToInt32(空)在c#返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆