奇法的行为 - 一个函数的ToString [英] Odd method behavior - ToString of a function

查看:89
本文介绍了奇法的行为 - 一个函数的ToString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码片段:

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";
  }
 }



测试()。的ToString ()返回ConsoleApplication1.Program + d__0,而不是预期的测试。

Test().ToString() returns "ConsoleApplication1.Program+d__0" instead of expected "test".

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

Test() method isn't even executed - just returns its name! The second method TestOk() works just fine.

这是怎么回事?

推荐答案

它的打印ToString方法由编译器生成的IEnumerable的实现 - 迭代器只是语法糖 - 产生一个真正的实现了IEnumerable的

It's printing the ToString method on the IEnumerable implementation generated by the compiler - Iterators are just syntactic sugar - a real implementation of IEnumerable is generated.

这篇关于奇法的行为 - 一个函数的ToString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆