仅供参考:您可以重构代码以简化它以获得完全相同的功能输出:
void Main()
{
int result;
Console.Write("Enter a Number : ");
while (!int.TryParse(Console.ReadLine(), out result))
{
Console.WriteLine("Please Enter Numbers Only.");
Console.Write("Enter a Number : ");
}
Console.WriteLine($"Entered String: {result} is a Number!");
Console.ReadKey();
}
如果您有充分的理由不使用 int.TryParse(例如,它缺少某些功能,或者这是一个要求您自己编写的练习),您可以使用上述替换 int.TryParse 来调用到IsNumericCustom,假设以下签名(或将int 类型更改为您需要处理的任何数据类型)。
public bool IsNumericCustom(string input, out int output)
{
//...
}
或者如果你只关心值是否是数字而不是解析值:
void Main()
{
string result;
Console.Write("Enter a Number : ");
//while (!int.TryParse((result = Console.ReadLine()), out _))
while (!IsNumericCustom((result = Console.ReadLine()))
{
Console.WriteLine("Please Enter Numbers Only.");
Console.Write("Enter a Number : ");
}
Console.WriteLine($"Entered String: {result} is a Number!");
Console.ReadKey();
}
public bool IsNumericCustom(string input)
{
//...
}
至于IsNumericCustom 中的逻辑,这实际上取决于您希望实现什么/为什么int.TryParse / decimal.TryParse 等不合适。这里有几个实现(使用不同的函数名)。
using System.Text.RegularExpressions; //https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex?view=netframework-4.7.2
//...
readonly Regex isNumeric = new Regex("^[+-]?\d*\.?\d*$", RegexOptions.Compiled); //treat "." as "0.0", ".9" as "0.9", etc
readonly Regex isInteger = new Regex("^[+-]?\d+$", RegexOptions.Compiled); //requires at least 1 digit; i.e. "" is not "0"
readonly Regex isIntegerLike = new Regex("^[+-]?\d*\.?\0*$", RegexOptions.Compiled); //same as integer, only 12.0 is treated as 12, whilst 12.1 is invalid; i.e. only an integer if we can remove digits after the decimal point without truncating the value.
//...
public bool IsNumeric(string input)
{
return isNumeric.IsMatch(input); //if you'd wanted 4.4 to be true, use this
}
public bool IsInteger(string input)
{
return isInteger.IsMatch(input); //as you want 4.4 to be false, use this
}
public bool IsIntegerLike(string input)
{
return isIntegerLike.IsMatch(input); //4.4 is false, but both 4 and 4.0 are true
}