Is there any built data type check methods in C# or we need to create our own methods to check?
Such a method gives me what I want, but do not know if I am writing ugly code. This method tries to convert textbox value to int,if fails it throws an error. if an error it return false which means it can not be converted to 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 ke开发者_运维问答ep 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
}
You can use int.TryParse()
, which returns a boolean saying whether the value was parsed correctly and an out parameter with the value. This method is faster than doing 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);
}
There's a Int32.TryParse
method which does almost the same.
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
精彩评论