首页 > 解决方案 > What happens when you concat a string with an IEnumerable

问题描述

I trust the compiler when refactoring, but stumbled upon something bizarre.

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

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

Can anyone explain what the reason would be for the compiler to accept this?

PS: now that you know it does not throw an exception, guess what the console will write as output. The answer here: https://dotnetfiddle.net/9nz8Bl

标签: c#compiler-errors

解决方案


无需猜测...

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

ToString()是由该类实现的虚拟方法System.Object(.NET 中的任何其他类型都从该方法派生,尽管有异常)。除非被覆盖,否则它的默认行为是返回正在调用它的实例的(完全限定的)类型名称。

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

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+<List>d__0 ”,本示例将产生以下输出:

List() 返回的可枚举类型:Program+<List>d__0
Program+<List>d__0wtf


推荐阅读