int.TryParse vs. other methods for determining if a char contains an int

六眼飞鱼酱① 提交于 2020-01-05 02:27:38

问题


When using the char datatype is there any reason one should use int.TryParse

int.TryParse(inputChar.ToString(), NumberStyles.Integer, 
                             CultureInfo.InvariantCulture, out curNum)

vs.

inputChar - '0'

And checking if the result is between 0-9?


回答1:


If you want to check if a char is a digit you should use Char.IsDigit:

if (Char.IsDigit(inputChar))
{ 
    // ...
}



回答2:


Well, two reasons why I would always use TryParse

  1. Using a well-tested library function is always better than re-inventing the wheel.
  2. The world outside the US doesn't speak "ASCII" - so there might be cases when the character code for 0 is not the smallest for a digit. In that case '9' - '0' != 9;. This is a might be. And because I'm too lazy to google this I'm on the safe side using TryParse :-)



回答3:


That's only about code clarity. int.TryParse clearly states its intent - I want to parse the string as number, if possible. It's relatively fast and safe.

If you find yourself getting stuck on TryParses, you can always write your own parsing. In some cases, it can save significant amount of time. For example, I've done such an implementation when parsing DBFs, which otherwise induced a lot of overhead from parsing bytes to strings, and strings to ints. Directly converting from the stream to int saved a lot of allocations and time.

After all, if you don't want to use built-in methods, why use .NET at all? Why not write everything in machine code? :))



来源:https://stackoverflow.com/questions/22044180/int-tryparse-vs-other-methods-for-determining-if-a-char-contains-an-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!