c# - 将字符串与 IEnumerable<string> 连接时会发生什么

标签 c# compiler-errors

我在重构时信任编译器,但偶然发现了一些奇怪的东西。

public static void Main()
{       
    Console.WriteLine(List() + "wtf"); // no compilation error
}

public static IEnumerable<string> List() {
    yield return "abc";
    yield return "xyz";
}

谁能解释一下编译器接受这个的原因是什么?

PS:现在您知道它不会抛出异常,猜猜控制台将写什么作为输出。答案在这里:https://dotnetfiddle.net/9nz8Bl

最佳答案

无需猜测...

当您执行 someValueOrObject + string 时,并且 someValueOrObject 不能隐式转换为字符串,则将调用 ToString() 方法在 someValueOrObject 上获取其字符串表示形式(相当于 someValueOrObject.ToString() + string)。

ToString()是由 System.Object 类(.NET 中的任何其他类型派生自该类, exceptions notwithstanding )实现的虚拟方法。除非被重写,否则它的默认行为是返回调用它的实例的(完全限定)类型名称。

为了更好地理解这一点,您可能需要运行此示例:

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {   
        var l = List();
        Console.WriteLine("Type of enumerable returned by List(): " + l.GetType().FullName);
        Console.WriteLine(l + "wtf"); 
    }

    public static IEnumerable<string> List() {
        yield return "abc";
        yield return "xyz";
    }
}

( https://dotnetfiddle.net/H0hl4O )

假设迭代器方法 List() 返回的编译器生成的可枚举对象的类型名称为“Program+d__0”,此示例将生成以下输出:

Type of enumerable returned by List(): Program+<List>d__0
Program+<List>d__0wtf

关于c# - 将字符串与 IEnumerable<string> 连接时会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56418060/

相关文章:

c# - Connection was not closed, Connection's current state is open error in foreach 循环

makefile - make 无法使用 openssl 构建 squid(使用了已弃用的函数)

compiler-errors - 如何在 Bison 码中解决此错误?

c++ - 编译错误boost属性树c++

c++ - 如何在Windows上使用MinGW编译C++?

c# - 是否可以为 WebService 进行设置安装?

c# - SynchronizationContext.Post 到 UI 方法

C# 泛型实例化

c# - 如何通过Visual Studio安装项目降级程序?

compiler-errors - mingw g++以错误的语言发出警告(德语而不是英语)