如何限制C#ReadKey条目?

如何限制C#ReadKey条目?,c#,C#,我一直试图找到一种方法来做到这一点,但迄今为止运气不太好 基本上,我要做的是限制用户的输入,这样他们就只能使用Console.Readkey输入1个字母和1个数字。例如,A1、E5、J9等。我希望避免它们像55或EE一样输入,因为这会在我的代码中导致错误。有没有一种简单的方法可以实现这一点?您需要编写自己的逻辑,就像检查每个输入值是否包含至少1个数字,1个字母是否为真,否则为假: string value = Console.ReadLine(); //you can also

我一直试图找到一种方法来做到这一点,但迄今为止运气不太好


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

您需要编写自己的逻辑,就像检查每个输入值是否包含至少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");
        }

这使用了一个
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;
      }
    }
  }
}
使用系统;
班级计划{
公共静态void Main(字符串[]args){
字符串值=string.Empty;
//获取一个字符,使用char.isleter作为检查函数。。。
GetChar(参考值,字符数);
//获取一个数字,使用char.isNumber作为检查函数。。。
GetChar(参考值,char.IsNumber);
WriteLine($“\n值:{value.ToUpper()}”);
}
//获取一个字符并将其附加到引用的字符串。
//check要求为所需的检查传递函数引用。
公共静态void GetChar(参考字符串值,Func检查){
//循环直到检查通过。
while(true){
char key=Console.ReadKey(true).KeyChar;
//如果支票通过。。。
如果(检查(键)){
//附加值
value+=key.ToString().ToUpper();
//打印它。。。
Console.Write(key.ToString().ToUpper());
//打破循环。
打破
}
}
}
}

Hi Owais,感谢您的回复,目前我的项目中有类似的代码。Value.contains部分,是否可以检查它是否包含一系列数字或字母?此逻辑工作正常,但如果您希望更具体地只检查一行代码中的数字或字母,则可以使用regext。此链接将帮助您检查Regex.IsMatch(hello,@“^[a-zA-Z]+$”;现在你必须自己尝试一些正则表达式,请检查上述链接。