简单字符串转换的例外情况 [英] Exception on a simple string conversion

查看:48
本文介绍了简单字符串转换的例外情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不确定这里发生了什么。

我将字符串转换为int时出现异常。



Not sure what is going on here.
I get an exception on the conversion of the string to int.

using System;
using System.Windows.Forms;

namespace WinFormsApp4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            int anInteger = Convert.ToInt32(textBox1.Text);
            label1.Text = anInteger.ToString();
        }
    }
}



我或我的Visual Studio是疯了吗?!


Is me or my Visual Studio is crazy?!

推荐答案

首先,不要使用Convert.ToInt32 - 改为使用TryParse方法:

Firstly, don't use Convert.ToInt32 - use the TryParse method instead:
int myInt = 0;
if (!int.TryParse(textBox1.Text, out myInt))
   {
   MessageBox.Show("Please enter a number!");
   return;
   }
label1.Text = myInt.ToString();

如果转换成功则返回true,否则返回false。



但是......有一个稍微深一点的问题。

你为什么要在构造函数中这样做?这个值是你在设计时设置的任何值,所以你真的不需要读它...

It returns true if the conversion succeeded, and false if it didn't.

But... there is a slightly deeper problem.
Why are you doing this in the constructor? The value is whatever you set at desgin time, so you really shouldn't need to read it yet...


这篇关于简单字符串转换的例外情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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