gpt4 book ai didi

c# - 为什么这个程序写一个空行而不是一个字符串值?

转载 作者:行者123 更新时间:2023-11-30 20:41:31 26 4
gpt4 key购买 nike

当我运行以下代码(我在 C# 面试中被问及)时,它没有输出任何内容。

有人可以解释这种行为吗?

class Program {
private static string result;

static void Main() {
SaySomething();
Console.WriteLine(result);
}

static async Task<string> SaySomething() {
await Task.Delay(5);
result = "Hello world!";
return “Something”;
}
}

我认为这个方法应该输出result,因为我正在调用

Console.WriteLine(result);

SaySomething() 方法调用完成后

最佳答案

因为 SaySomethingasync 当您点击 await Task.Delay(5) 并且因此在它更改 result 的值之前点击 Console.WriteLine(result)。只需将其更改为 SaySomething().Wait(); 即可。

关于c# - 为什么这个程序写一个空行而不是一个字符串值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32257510/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com