给出如下运行方式:
internal static void DefaultShow(object o) {
if ( o is IEnumerable) {
StringBuilder sb = new StringBuilder(1024);
foreach(var i in o as IEnumerable ) {
sb.Append($"{i}|");
}
Console.WriteLine(sb.ToString());
} else {
Console.WriteLine(o.ToString());
}
}
DefaultShow("a,b,c".Split(","));
显示:
"a|b|c|"
时间:
internal static void DefaultShow(object o) {
if ( o is IEnumerable) {
Console.WriteLine(string.Join("|", o as IEnumerable));
} else {
Console.WriteLine(o.ToString());
}
}
DefaultShow("a,b,c".Split(","));
显示:
System.String[]
最佳答案
如果您查看 list of overloads的 string.Join
, 他们都不接受 IEnumerable
.有一个接受 IEnumerable<string>
,仅此而已。
因此,您调用string.Join
将绑定(bind)到需要 params object[]
的重载.从方法的角度来看,object[]
只有一个元素,即 IEnumerable
, 所以它调用 ToString()
就此返回。
您可能想要转换 IEnumerable
到IEnumerable<object>
首先,然后通过 ToString
将所有内容转换为字符串:
internal static void DefaultShow(object o) {
if ( o is IEnumerable) {
Console.WriteLine(string.Join("|", (o as IEnumerable).Cast<object>().Select(x => x.ToString())));
} else {
Console.WriteLine(o.ToString());
}
}
关于c# - 为什么 IEnumerable 没有被 string.Join 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56668391/