c# - 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
解决方案
无需猜测...
当您这样做时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
推荐阅读
- regex - 正则表达式仅选择此字符串中的数字并忽略包含数字的单词
- javascript - 如果可以在 WebGL/WebGL2 中使用大于 1 的整数刻度
- filesystems - NTFS MFT 数据运行
- ms-access - 创建小型 MS Access 数据库,其中相同的客户/公司在多个状态下运营
- amazon-web-services - 在 AWS SES 中删除/阻止传出电子邮件
- c# - 如何从 CloudFile(Azure 文件存储)读取数据?
- amazon-web-services - Ansible 使用 AWS 交互引发异常
- c - 将表单中的复选框链接回 MVC/Razor 页面中类的字符串属性
- vue.js - 将 NPM 包组件中的样式包含到 WebComponent 中
- r - 选择变量时selectInput不起作用