【问题标题】:How to check if input is string or byte in C#?如何在C#中检查输入是字符串还是字节?
【发布时间】:2016-08-26 11:51:45
【问题描述】:

我做了一个非常简单的程序,用户需要写下他的名字和年龄。然后会弹出一个消息框并显示姓名和年龄。 (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();
    }
}

我该怎么做:如果年龄是一个字符串,会弹出一个消息框说“年龄不是数字,用户需要再试一次”?

【问题讨论】:

标签: c# .net winforms c#-6.0


【解决方案1】:
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

【讨论】:

    【解决方案2】:

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

        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 会将年龄(out 参数)设置为 0(零)

    【讨论】:

      【解决方案3】:

      试试这个:

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-12-04
          • 1970-01-01
          • 2018-05-03
          • 2020-03-20
          • 2013-08-12
          • 2015-04-13
          • 1970-01-01
          • 2014-12-20
          相关资源
          最近更新 更多