C# 用户控制整数的最佳方法

C# 用户控制整数的最佳方法,c#,C#,我做了这件事,想知道是否有更好的方法 ```Console.WriteLine("Name me."); String cn = Console.ReadLine(); Console.WriteLine($"I like this name ,{cn}, What is my funcion? "); String fn = Console.ReadLine(); Console.WriteLine($"I will l

我做了这件事,想知道是否有更好的方法

```Console.WriteLine("Name me.");
   String cn = Console.ReadLine();
   Console.WriteLine($"I like this name ,{cn}, What is my funcion? ");
   String fn = Console.ReadLine();
   Console.WriteLine($"I will learn how to do {fn} for you.");
   Console.WriteLine("I Will double any number you give me.");
   int a = Convert.ToInt32(Console.ReadLine());
   int b = 2;
   Console.WriteLine(a * b); 
   ```

Best是主观的,但代码存在一些问题:

输入的任何非数字字符串都将引发异常 任何十进制数字字符串也将引发异常。 <>而不是使用TrimetoTeN32,而是应该考虑使用TyPARSE方法。此方法接受一个字符串和一个out参数,如果成功,则将其设置为转换后的值,否则为0,并返回一个表示成功的bool。如果我们使用decimal类型,我们将得到一个精度非常高的数字,并且可以包含小数

然后,如果我们创建一个带有循环的方法,该循环使用TryParse的结果作为条件,那么我们可以循环,直到用户输入正确的数字

我们还可以允许用户传入一个验证方法,以便他们可以指定有效数字的规则是什么,即它是否必须大于零,或者必须是奇数,等等

然后我们可能会得到这样的结果:

public static decimal GetDecimalFromUser(string prompt, 
    Func<decimal, bool> validator = null)
{
    bool isValid = true;
    decimal result;

    do
    {
        if (!isValid)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Invalid input, please try again.");
            Console.ResetColor();
        }
        else isValid = false;

        Console.Write(prompt);
    } while (!decimal.TryParse(Console.ReadLine(), out result) &&
                (validator == null || !validator.Invoke(result)));

    return result;
}
现在我们可以编写用户不能输入无效输入的代码了!在使用中,代码将如下所示:

string name = GetStringFromUser("Please give me a name: ");
string fn = GetStringFromUser($"I like this name, {name}. What is my function? ");
Console.WriteLine($"I will learn how to do {fn} for you.");
decimal input = GetDecimalFromUser("Please enter a number and I will double it: ");
Console.WriteLine($"{input} * 2 = {input * 2}");

更好的方法是非常主观的。如果您需要更多的速记,可以使用Console.Writeline2*CConvert.ToInt32Console.ReadLine;
string name = GetStringFromUser("Please give me a name: ");
string fn = GetStringFromUser($"I like this name, {name}. What is my function? ");
Console.WriteLine($"I will learn how to do {fn} for you.");
decimal input = GetDecimalFromUser("Please enter a number and I will double it: ");
Console.WriteLine($"{input} * 2 = {input * 2}");