C# 如何限制控制台输入的字符数?C

C# 如何限制控制台输入的字符数?C,c#,console-application,user-input,C#,Console Application,User Input,基本上,在字符开始被抑制之前,我希望Console.ReadLine中最多出现200个字符,供用户输入。我希望它像TextBox.MaxLength一样,除了控制台输入。我该怎么办 我不想做input.substring0200 已解决: 我使用了自己的ReadLine函数,它是Console.ReadKey的一个循环 从本质上看,它是这样的: StringBuilder sb = new StringBuilder(); bool loop = true; while (loop) {

基本上,在字符开始被抑制之前,我希望Console.ReadLine中最多出现200个字符,供用户输入。我希望它像TextBox.MaxLength一样,除了控制台输入。我该怎么办

我不想做input.substring0200

已解决:

我使用了自己的ReadLine函数,它是Console.ReadKey的一个循环

从本质上看,它是这样的:

StringBuilder sb = new StringBuilder();
bool loop = true;
while (loop)
{
    ConsoleKeyInfo keyInfo = Console.ReadKey(true); // won't show up in console
    switch (keyInfo.Key)
    {
         case ConsoleKey.Enter:
         {
              loop = false;
              break;
         }
         default:
         {
              if (sb.Length < 200)
              {
                  sb.Append(keyInfo.KeyChar);
                  Console.Write(keyInfo.KeyChar);
              }
              break;
         }
    }
}

return sb.ToString();

谢谢大家

没有办法限制输入ReadLine的文本。正如政府解释的那样

一行定义为一系列的 后面跟有马车的字符 返回十六进制0x000d,一行 馈送十六进制0x000a,或 Environment.NewLine的值

您可以做的是在循环中使用ReadKey,该循环不允许超过200个字符,如果用户键入Environment.NewLine,则会中断。

如果您可以使用Console.Read,则可以循环,直到达到200个字符或输入enter键为止

StringBuilder sb = new StringBuilder();
int i, count = 0;

while ((i = Console.Read()) != 13)   // 13 = enter key (or other breaking condition)
{
    if (++count > 200)  break;
    sb.Append ((char)i);
}
编辑

结果表明,Console.ReadKey比Console.Read更受欢迎


总体情况如何?