简体   繁体   中英

int.Parse on negative number results in exception

This line of code:

int.Parse("-1");

Results in a FormatException that says "Input string was not in the correct format" when i run it on a device. On the emulator it works just fine. I've tested this with a bunch of devices, and the only one that is working as intended (ie returns an int with value -1) is the Samsung Galaxy Nexus, running android 4.2.1. All these devices generates an exception:

  • Google Nexus 7 (4.3)
  • Samsung S3 (4.1.2)
  • Samsung Galaxy Tab (4.0.4)
  • LG P970 (2.2.2)
  • HTC Sensation (2.3.4)

I also tried to download the app C#Shell from playstore on a device, and enter the line above, the result is the same:

C#Shell屏幕截图

Do anyone know why this happens, or what can be done to resolve this issue?

Update:

The reason i'm investigating this issue is because our app is requesting a JSON from our servers, and it contains a bunch of negative numbers. We then use ServiceStack to parse the JSON, which results in all negative numbers becoming 0. ServiceStack has no way of setting a FormatSpecifier.

int.Parse("-1", CultureInfo.InvariantCulture) seems to work as intended on all devices regardless of what language they are using, but int.Parse("-1", new CultureInfo("sv-SE")) does not.

I find this a bit odd, since int.Parse("-1", new CultureInfo("sv-SE")) works on other platforms where we're not using xamarin or mono.

I ended up committing a fix to ServiceStack:

https://github.com/ServiceStack/ServiceStack.Text/pull/365

Update:

And now Xamarin also fixed it:

https://bugzilla.xamarin.com/show_bug.cgi?id=14185

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM