C# 根据条件重新运行代码块

C# 根据条件重新运行代码块,c#,C#,我正在开发一个基本的控制台程序,如下所示。我对后一段代码无法工作感到相当恼火。检查用户输入的年龄并从Console.WriteLine重新运行代码的最佳方法是什么(“好的,现在请输入您的年龄。”);添加到if语句 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Practice { c

我正在开发一个基本的控制台程序,如下所示。我对后一段代码无法工作感到相当恼火。检查用户输入的年龄并从Console.WriteLine重新运行代码的最佳方法是什么(“好的,现在请输入您的年龄。”);添加到if语句

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Practice
{
    class Program
    {
        static void Main(string[] args)
        {
           Console.WriteLine("Thank you for participating in this survey. Please take a moment to fill out the required information.");
           Console.WriteLine("Please Type Your Name");

            string name = Console.ReadLine();

            Console.WriteLine("Okay. Now please enter your age.");

            string age = Console.ReadLine();

            Console.WriteLine("Your information has been submitted.");

            Console.WriteLine("Name: " + name + "\n" + "Age: " + age);

            Console.ReadLine();

            int newAge = Int32.Parse(age);

            if (newAge => 18) 
            {

            }

        }
    }
}
替换此项:

 int newAge = Int32.Parse(age);
用这个

 int newAge = Convert.ToInt32(age);
。 如果您想更好地编写代码,请使用catch

try
{
int newAge = Convert.ToInt32(age);
}
catch(FormatException)
{
//do something
}

您还可以使用TryParse,它为您进行错误测试,并将解析后的值作为out参数返回。由于TryParse返回bool值,因此可以轻松检查转换是否有效

string age = null;
int ageValue = 0;
bool succeeded = false;

while (!succeeded)
{
    Console.WriteLine("Okay, now input your age:");
    age = Console.ReadLine();
    succeeded = int.TryParse(age, out ageValue);
}
你也可以把它倒过来做。。。当

string age = null;
int ageValue = 0;
do
{
    Console.WriteLine("Okay, now input your age:");
    age = Console.ReadLine();
} while (!int.TryParse(age, out ageValue));

您似乎已经知道如何将字符串转换为int。请修复您的标题,使其正确反映您实际请求帮助的内容。请看,我仍然存在if语句出错的问题,您应该使用
=
而不是
=>