首页 > 解决方案 > 如何查找从键盘输入的值的类型?

问题描述

如何使用方法在 C# consol 应用程序中显示从键盘输入的值的类型?

static void Main(string[] args)
{
    int yas;
    Console.Write("Enter Your Age: ");

    yas = int.Parse(Console.ReadLine());

    Console.WriteLine("You're {0} years old.", yas);

}

在示例中的应用程序中,我只希望您的用户输入数字数据,但我尝试使用 typeof 来执行它会出错。你能帮助我吗?

我不想更改变量的类型。我想让你的用户再次想要价值而不是 int。输入值时解析错误

标签: c#console-applicationtypeof

解决方案


我想让您的用户在输入值时再次想要值而不是 int.parse 错误

您可以使用评论中提到的方法不断要求输入,直到正确为止:

static void Main(string[] args)
{
    int yas;

    do { // until the user input is valid, keep asking
        Console.Write("Yaşınız Giriniz: ");
    } while (!int.TryParse(Console.ReadLine(), out yas));

    Console.WriteLine("Demek {0} yaşınızdasınız", yas);
}

推荐阅读