问题
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
- Using a well-tested library function is always better than re-inventing the wheel.
- 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 usingTryParse
:-)
回答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 TryParse
s, 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