如何在c#中检查输入是字符串还是字节

本文关键字:字符串 字节 输入 检查 | 更新日期: 2023-09-27 18:04:03

我做了一个非常简单的程序,用户需要写他的名字和年龄。然后弹出一个消息框,显示姓名和年龄。(https://i.stack.imgur.com/FOdF5.jpg)

public partial class MySecondApplication : Form
{
    public MySecondApplication()
    {
        InitializeComponent();
    }
    private void txtName_TextChanged(object sender, EventArgs e)
    {
        txtAge.Enabled = true;
    }
    private void txtAge_TextChanged(object sender, EventArgs e)
    {
        cmdSubmit.Enabled = true;
    }
    private void cmdSubmit_Click(object sender, EventArgs e)
    {
        var name = txtName.Text;
        var age = Convert.ToByte(txtAge.Text);
        MessageBox.Show($"Your name is {name} and You're {age} years old.");
    }
    private void cmdExit_Click(object sender, EventArgs e)
    {
        Close();
    }
}

我怎么能做到这一点:如果年龄是一个字符串,弹出一个消息框,说"年龄不是一个数字,用户需要再试一次"?

如何在c#中检查输入是字符串还是字节

var name = txtName.Text;
Byte outAge;
bool result= Byte.TryParse(txtAge.Text, NumberStyles.Integer,null as IFormatProvider, out outAge);
if (!result)
{
//show your message box;
}
else
{
var age=outAge;
}

请点击下面的链接查看简要说明

https://msdn.microsoft.com/en-us/library/tkktxbeh (v = vs.110) . aspx

从技术上讲,转换没有什么问题,如果所有数据都有效,这将工作。

    private void cmdSubmit_Click(object sender, EventArgs e)
    {
      var name = txtName.Text;
      var age = Convert.ToByte(txtAge.Text);
      MessageBox.Show($"Your name is {name} and You're {age} years old.");
    }

有几种方法可以验证您的数据,下面是您可能想要使用的另一种方法。

    private void cmdSubmit_Click(object sender, EventArgs e)
    {
      string name = txtName.Text;
      short age; //This is an Int16 with a range of -32,768 to +32,767
      short.TryParse(txtAge.Text,out age);
      string ageStatement = age == 0 ? "your age is unknown" : 
                                      $"you're {age} years old";
      MessageBox.Show($"Your name is {name} and {ageStatement}.");

TryParse

    short.TryParse(txtAge.Text,out age);

如果字符串数据在txtAge。文本不是数字,TryParse会将age (out参数)设置为0(零)

试试这个:

private void cmdSubmit_Click(object sender, EventArgs e)
{
    var name = txtName.Text;
    int age;
    if(Int32.TryParse("txtAge.Text, out age))
    {
        MessageBox.Show($"Your name is {name} and You're {age} years old.");
    }
    else
    {
        MessageBox.Show("Enter valid age");         
    }
}

尝试使用NumericUpDown控件,将最小值和最大值设置为合理的值,并且不重新实现验证和解析