【问题标题】:How do I Limit C# ReadKey entries?如何限制 C# ReadKey 条目?
【发布时间】:2021-01-06 08:50:26
【问题描述】:

我一直在尝试找到一种方法来做到这一点,但到目前为止运气不佳。

基本上我要做的是限制用户的条目,以便他们只能使用 Console.Readkey 输入 1 个字母和 1 个数字。因此,例如,A1、E5、J9 等。我想避免它们像 55 或 EE 这样输入,因为这会导致我的代码出错。有没有简单的方法来实现这一点?

【问题讨论】:

    标签: c#


    【解决方案1】:

    这使用GetChar 方法,该方法要求您传递一个函数来检查输入是字符还是数字。在输入有效条目之前,它不允许您继续操作。

    using System;
    
    class Program {
      public static void Main (string[] args) {
        string value = string.Empty;
    
        // Get a character, using char.IsLetter as the checking function...
        GetChar(ref value, char.IsLetter);
    
        // Get a number, using char.isNumber as the checking function... 
        GetChar(ref value, char.IsNumber);
    
        Console.WriteLine($"\nValue: {value.ToUpper()}");
      }
    
      // Get a character and append it to the referenced string.
      // check requires that you pass a function reference for the required check.
      public static void GetChar(ref string value, Func<char, bool> check) {
    
        // Loop until the check passes.
        while(true) {
          char key = Console.ReadKey(true).KeyChar;
    
          // If check passes...
          if(check(key)) {
    
            // Append the value
            value += key.ToString().ToUpper();
    
            // Print it...
            Console.Write(key.ToString().ToUpper());
    
            // Break out of the loop.
            break;
          }
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      您需要编写自己的逻辑,就像检查每个输入值是否包含至少 1 个数字和 1 个字母为真,否则为假:

       string value = Console.ReadLine();
              //you can also check value.length and redirect if length greater than 2
              if (value.Length > 2)
              {
                  Console.WriteLine("Please enter correct value");
                  return;
              }
              if (value.Contains("Your Number"))
              {
                  if (value.Contains("Your Letter"))
                  {
                      //your code goes here
                  }
                  else
                  {
                      Console.WriteLine("Please Enter Correct Value");
                  }
              }
              else
              {
                  Console.WriteLine("Please Enter Correct Value");
              }
      

      【讨论】:

      • 您好 Owais,感谢您的回复,目前我的项目中有类似的代码。 Value.contains 部分,是否可以检查它是否包含一系列数字或字母?
      • 这个逻辑可以正常工作,但如果你想更具体地只检查一行代码中的数字或字母,你可以使用正则表达式
      • Regex.IsMatch(你好,@"^[a-zA-Z]+$");现在您必须自己尝试一些正则表达式公式,请检查上述链接。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 2017-05-05
      • 2020-01-12
      • 2021-12-03
      • 2013-12-02
      相关资源
      最近更新 更多