【发布时间】:2021-01-06 08:50:26
【问题描述】:
我一直在尝试找到一种方法来做到这一点,但到目前为止运气不佳。
基本上我要做的是限制用户的条目,以便他们只能使用 Console.Readkey 输入 1 个字母和 1 个数字。因此,例如,A1、E5、J9 等。我想避免它们像 55 或 EE 这样输入,因为这会导致我的代码出错。有没有简单的方法来实现这一点?
【问题讨论】:
标签: c#
我一直在尝试找到一种方法来做到这一点,但到目前为止运气不佳。
基本上我要做的是限制用户的条目,以便他们只能使用 Console.Readkey 输入 1 个字母和 1 个数字。因此,例如,A1、E5、J9 等。我想避免它们像 55 或 EE 这样输入,因为这会导致我的代码出错。有没有简单的方法来实现这一点?
【问题讨论】:
标签: c#
这使用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;
}
}
}
}
【讨论】:
您需要编写自己的逻辑,就像检查每个输入值是否包含至少 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");
}
【讨论】: