我如何做一个 bool 语句只允许文本?我有此代码只允许用户输入数字但不知道如何输入文本。
bool Dest = double.TryParse(this.xTripDestinationTextBox.Text, out Miles);
bool MilesGal = double.TryParse(this.xTripMpgTextBox.Text, out Mpg);
bool PriceGal = double.TryParse(this.xTripPricepgTextBox.Text, out Price);
最佳答案
更新:看你的评论我建议你阅读这篇文章:
User Input Validation in Windows Forms
原始答案:最简单的方法(至少如果您使用的是 .NET 3.5)是使用 LINQ:
bool isAllLetters = s.All(c => char.IsLetter(c));
在旧的 .NET 版本中,您可以创建一个方法来为您执行此操作:
bool isAllLetters(string s)
{
foreach (char c in s)
{
if (!char.IsLetter(c))
{
return false;
}
}
return true;
}
您也可以使用正则表达式。如果你想允许 Unicode 中定义的任何字母,那么你可以使用这个正则表达式:
bool isOnlyLetters = Regex.IsMatch(s, @"^\p{L}+$");
如果你想限制到 A-Z 那么你可以使用这个:
bool isOnlyLetters = Regex.IsMatch(s, @"^[a-zA-Z]+$");
关于c# - 允许用户只输入文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2844371/