为什么C#没有“普通”整数输入?

时间:2019-06-01 00:27:21

标签: c# input integer

很明显,我怀疑这里的大多数人(如果有)是否在开发C#语言方面有所帮助。但是我目前正在学习该语言,并且我很快注意到没有办法自动获取整数输入,例如在C / C ++中。取而代之的是,您需要读取一个char / string,然后将其转换为整数才能使用(或者代替整数,而是使用double或您拥有的东西)。

我对编程语言设计并不了解很多,所以我不知道为什么将其包含在语言中,因为它似乎不太直观(至少对我而言)。

例如,在以下代码中:

int myInt = Console.Read();

这只是返回我将输入的任何数字的ASCII值。相反,我必须这样做:

int myInt = Convert.ToInt32(Console.Read());

能够使用用户输入的实际整数。

我希望得到任何答案! 谢谢!

1 个答案:

答案 0 :(得分:0)

  

原因是,由于在C#中解析表示数字的字符串是非常简单的,因此不值得花费大部分精力来实现这种功能以及大多数用例所需要的灵活性,只是为了获得一点便利。以各种形式转化为实际数字。*

*受过教育的猜测,@ elgonzo的称赞


例如:

private static int GetIntFromUser(string prompt, Func<int, bool> validator = null)
{
    int result;
    var cursorTop = Console.CursorTop;

    do
    {
        ClearSpecificLineAndWrite(cursorTop, prompt);
    } while (!int.TryParse(Console.ReadLine(), out result) ||
             !(validator?.Invoke(result) ?? true));

    return result;
}

private static void ClearSpecificLineAndWrite(int cursorTop, string message)
{
    Console.SetCursorPosition(0, cursorTop);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, cursorTop);
    Console.Write(message);
}

很容易从用户那里获得强类型的int,甚至可以向其添加一些验证:

// Get a number from the user from 1 - 10. They will not
// be able to proceed until a valid number is entered
int userInput = GetIntFromUser("Enter a number from 1 to 10: ", x => x > 0 && x < 11);
相关问题