简体   繁体   English

奇数方法行为 - 函数的ToString

[英]Odd method behavior - ToString of a function

Consider this code snippet: 请考虑以下代码段:

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() returns "ConsoleApplication1.Program+d__0" instead of expected "test". Test().ToString()返回“ConsoleApplication1.Program + d__0”而不是预期的“test”。

Test() method isn't even executed - just returns its name! Test()方法甚至没有执行 - 只返回它的名字! The second method TestOk() works just fine. 第二种方法TestOk()工作得很好。

What is going on? 到底是怎么回事?

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

The Test() method returns an IEnumerable(char) which in this case is a compiler generated object. Test()方法返回一个IEnumerable(char),在本例中是一个编译器生成的对象。 It's ToString() method is the default for an object and returns the type name, also compiler generated. 它的ToString()方法是对象的默认方法,并返回类型名称,也是编译器生成的。

The yeild return method is treated differently be the compiler - if you check the compiled assembly using reflector whats going on here becomes a little clearer: yeild返回方法与编译器的处理方式不同 - 如果使用反射器检查编译的程序集,这里的内容会变得更加清晰:

private static IEnumerable<char> Test()
{
    return new <Test>d__0(-2);
}

Wheras TestOk returns a string, Test instead returns a class that the compiler generates for you. Wheras TestOk返回一个字符串, Test代替返回编译器为您生成的类。 What you are seeing is the default string representation of that class. 您看到的是该类的默认字符串表示形式。

其他答案已经解释了当前的行为,但是如果你想获得预期的行为,那么你可以将IEnumerable<char>转换为数组并使用带有char[]的String构造函数,而不是使用ToString():

Console.WriteLine(new string(Test().ToArray()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM