如何只允许将数字输入到我的C#控制台应用程序中?

Sar*_*rah 11 c# console-application

Console.WriteLine("Enter the cost of the item");                           
string input = Console.ReadLine();
double price = Convert.ToDouble(input);
Run Code Online (Sandbox Code Playgroud)

您好,我希望禁用键盘按钮,AZ,支架,问号等.我想要它,如果你输入它,它将不会出现在控制台中.我只希望数字1-9出现.这是在C#Console应用程序中.谢谢您的帮助!

Joh*_*Woo 14

试试这段代码

string _val = "";
Console.Write("Enter your value: ");
ConsoleKeyInfo key;

do
{
    key = Console.ReadKey(true);
    if (key.Key != ConsoleKey.Backspace)
    {
        double val = 0;
        bool _x = double.TryParse(key.KeyChar.ToString(), out val);
        if (_x)
        {
            _val += key.KeyChar;
            Console.Write(key.KeyChar);
        }
    }
    else
    {
        if (key.Key == ConsoleKey.Backspace && _val.Length > 0)
        {
            _val = _val.Substring(0, (_val.Length - 1));
            Console.Write("\b \b");
        }
    }
}
// Stops Receving Keys Once Enter is Pressed
while (key.Key != ConsoleKey.Enter);

Console.WriteLine();
Console.WriteLine("The Value You entered is : " + _val);
Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)

  • 我回头看了这个,它帮助我另一个问题.随着我学习更多C#,我更了解你在做什么.在了解所有这一切之前,我还有很长的路要走! (2认同)