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

How to check if input is string or byte in C#?

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

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();
    }
}

我该怎么做:如果 age 是一个字符串,会弹出一个消息框并显示 "the age is not a number and the user needs to try again"?

试试这个:

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");         
    }

}
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;
}

请查看下面link的简要说明

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

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

从技术上讲,convert 没有任何问题,如果所有数据都有效,这将起作用。

    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.Text 中的字符串数据不是数字,TryParse 会将年龄(输出参数)设置为 0(零)