gpt4 book ai didi

c# - 奇怪的方法行为 - 函数的 ToString

转载 作者:太空狗 更新时间:2023-10-30 00:17:09 24 4
gpt4 key购买 nike

考虑这个代码片段:

class Program {
static void Main(string[] args) {
Console.WriteLine(Test().ToString());
}

static IEnumerable<char> Test() {
foreach (var ch in "test")
yield return ch;
}
static IEnumerable<char> TestOk() {
return "test";
}
}

Test().ToString() 返回“ConsoleApplication1.Program+d__0”而不是预期的“test”。

Test() 方法甚至没有执行 - 只是返回它的名字!第二种方法 TestOk() 工作得很好。

这是怎么回事?

最佳答案

它在编译器生成的 IEnumerable 实现上打印 ToString 方法 - 迭代器只是语法糖 - 生成了 IEnumerable 的真正实现。

关于c# - 奇怪的方法行为 - 函数的 ToString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3483745/

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