在C#中是否有任何构建的数据类型检查方法,或者我们需要创建自己的方法来检查?

时间:2011-03-01 11:34:29

标签: c# .net validation

这样的方法给了我想要的东西,但不知道我是否在编写丑陋的代码。此方法尝试将文本框值转换为int,如果失败则会引发错误。如果一个错误它返回false意味着它不能转换为int。


namespace icol
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            AllUse myMethods = new AllUse();
            if (myMethods.isThisInt(textBox1.Text))
            {
                MessageBox.Show(textBox1.Text);
                // if this int, you can keep writing further your program's logic
            }
            else {

                MessageBox.Show("This textbox value can not be converted to int!");
            }
        }
    }

    public class AllUse{

        public bool isThisInt(string x) {
            try {
                Convert.ToInt32(x);
                return true;
            }
            catch (Exception err ){
                string y = err.Message; // do not know what to do with err
                return false;
            }      
        } //method

    } // class
}

3 个答案:

答案 0 :(得分:4)

您可以使用int.TryParse(),它返回一个布尔值,表示该值是否已正确解析,以及带有值的out参数。这种方法比try / catch更快。

int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
    Console.WriteLine("Converted '{0}' to {1}.", value, number);         
}
else
{
    if (value == null) value = ""; 
    Console.WriteLine("Attempted conversion of '{0}' failed.", value);
}

答案 1 :(得分:0)

有一种Int32.TryParse方法几乎完全相同。

答案 2 :(得分:0)

int number;
bool result = Int32.TryParse(textBox1.Text, out number);

if (result)
{
   // Do something
}
else
{
   // Do something else
}

http://msdn.microsoft.com/en-us/library/f02979c7.aspx