输入无效输入时,Tryparse不使用else语句

时间:2018-10-08 00:49:04

标签: c# tryparse

else语句“重量必须大于0”正在工作,但是如果我在PackageWeight.Text文本框中输入字母,则else语句将不会显示。

if (decimal.TryParse(PackageWeight.Text, out weight))
{
    if (weight > 0)
    {
        weightcost = pound * weight;
        Weight.Text = weightcost.ToString("c");
    }
    else
    {
        MessageBox.Show("Weight must be greater than 0.");
    }
}
else
{
    MessageBox.Show("Invalid input for weight.");
}

1 个答案:

答案 0 :(得分:0)

        static void Main(string[] args)
        {
            Parse("1");
            Parse("-1");
            Parse("DDD");
        }

        private static void Parse(string x)
        {
            if (decimal.TryParse(x, out decimal weight))
            {
                if (weight > 0)
                {
                    var weightcost = 2 * weight;
                    Console.WriteLine(weightcost.ToString("c"));
                }
                else
                {
                    Console.WriteLine("Weight must be greater than 0.");
                }
            }
            else
            {
                Console.WriteLine("Invalid input for weight.");
            }
        }

产生正确的输出:

enter image description here