函数returns只取输入变量的第一个值

Function returns only the first value of the input variable

我对可变结果有疑问。我有一个要求输入数字的功能。它 return 是 AskForNumber 函数的第一个输入。任何人都可以帮助我吗?我是 C# 的新手,不知道我应该知道的很多细节。希望得到你的帮助:))

这是主要功能

static void Main() {
    string playersNum = AskForNumber(numberLength);
    Console.WriteLine(playersNum);
}

这就是请求数字的函数

static string AskForNumber(int numberLength) {
    Console.WriteLine($"Write number of Length {numberLength}");
    string number_string = Console.ReadLine();

    if (!CheckCondition(numberLength, number_string)) {
        AskForNumber(numberLength);
    }
    return number_string;       
}

那么应该在 CheckCondition 函数中检查数字,return 是真还是假

static bool CheckCondition(int length, string number_string) {

    if (!int.TryParse(number_string, out int number)) {
        Console.WriteLine("thats nan!!");
        return false;

    } else if (number_string.Length != length) {
        Console.WriteLine($"number's length must be {length} digits");
        return false;
    }
    return true;
}

取决于它应该 return 变量中的数字只有当它为真时才

这是终端的结果

Write number of the length 4
qwerty
Thats nan!
1234

qwerty (Thats the result of the Console.WriteLine(playersNum); in the main function)

这是因为你在调用AskForNumber()

Main 中您是第一次呼叫 AskForNumber() 并输入“querty”。那么 CheckCondition 方法 return 是错误的,因为它不是一个数字,并且您正在再次调用 AskForNumber()。然后输入“1234”,其中 CheckCondition return 为真,因此“1234”在第二次 AskForNumber() 时被重新调整 。 “1234”是 returned 到第一次调用 AskForNumber() 时,您不对 returned 值执行任何操作,只需保留 if 块和 return 存储在 number_string 中的值。但是因为您没有将第二次调用 AskForNumber() 的 return 值分配给此变量,它仍然包含“qwerty”,因此 Main 接收“qwerty”并打印它。

只需将您的代码更改为

static string AskForNumber(int numberLength) {
    Console.WriteLine($"Write number of Length {numberLength}");
    string number_string = Console.ReadLine();

    if (!CheckCondition(numberLength, number_string)) {
        return AskForNumber(numberLength); // Return statement added here
    }
    return number_string;       
}

它将按预期工作。

您可以 return 值然后调用方法,或者在 return 值时调用方法。

static string AskForNumber(int numberLength) {
Console.WriteLine($"Write number of Length {numberLength}");
string number_string = Console.ReadLine();

if (!CheckCondition(numberLength, number_string)) {
    return AskForNumber(numberLength); /* this will call the method in a return statement 
}
return number_string;       
}