C#中是否有内置的数据类型检查方法,或者我们需要创建自己的方法来检查?
这种方法给了我想要的东西,但不知道我是否在写难看的代码。此方法尝试将textbox值转换为int,如果失败,将抛出错误。如果出现错误,则返回false,这意味着无法将其转换为intC#中是否有内置的数据类型检查方法,或者我们需要创建自己的方法来检查?,c#,.net,validation,C#,.net,Validation,这种方法给了我想要的东西,但不知道我是否在写难看的代码。此方法尝试将textbox值转换为int,如果失败,将抛出错误。如果出现错误,则返回false,这意味着无法将其转换为int namespace icol { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private vo
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
}
有一种方法的作用几乎相同。有一种方法的作用几乎相同
int number;
bool result = Int32.TryParse(textBox1.Text, out number);
if (result)
{
// Do something
}
else
{
// Do something else
}
您可以使用,它返回一个布尔值,说明该值是否被正确解析,并返回一个带有该值的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);
}
您可以使用,它返回一个表示值是否正确解析的布尔值和一个带有该值的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);
}
聪明人,非常感谢你的快速反应。聪明人,非常感谢你的快速反应。