在C#中将字符串转换为int错误 [英] convert string to int error in c#

查看:81
本文介绍了在C#中将字符串转换为int错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,我正在尝试将String转换为Integer.

Hello I am trying to convert String to Integer.

下面的代码显示了我尝试将字符串转换为整数的部分.

The code below shows a part from where I am trying to convert my string to integer.

if (other.gameObject.CompareTag("PickUp"))
{
    if ( checkpointboolean == false)
    {
        string pickupName = other.ToString(); //other = Pickup4
        //Remove first 6 letters thus remaining with '4'
        string y = pickupName.Substring(6); 
        print(y); // 4 is being printed
        int x = 0;
        int.TryParse(y, out x);
        print (x); // 0 is being printed

我还尝试了以下代码,而不是"0",但出现以下错误:

I also tried the below code and instead of '0' I am getting the following error:

if (other.gameObject.CompareTag("PickUp"))
{
    if ( checkpointboolean == false)
    {
        //Get Object name ex: Pickup4
        string pickupName = other.ToString();
        //Remove first 6 letters thus remaining with '4'
        string y = pickupName.Substring(6); 
        print(y);
        int x = int.Parse(y);

FormatException:输入字符串的格式不正确System.Int32.Parse(System.String s)

FormatException: Input string was not in the correct format System.Int32.Parse (System.String s)

推荐答案

int.TryParse 返回一个布尔值,如果成功则返回true,否则返回false.您需要将其包装在if块中,然后使用该逻辑进行操作.

int.TryParse returns a boolean, true if it succeeded and false if not. You need to wrap this in a if block and do something with that logic.

if(int.TryParse(y, out x))
    print (x); // y was able to be converted to an int
else
    // inform the caller that y was not numeric, your conversion to number failed

至于为什么不转换您的电话号码,我不敢说,直到您发布了字符串值是什么.

As far as why your number is not converted I could not say until you post what the string value is.

这篇关于在C#中将字符串转换为int错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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