c# - 为什么 IEnumerable 没有被 string.Join 枚举

标签 c#

给出如下运行方式:

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 overloadsstring.Join , 他们都不接受 IEnumerable .有一个接受 IEnumerable<string> ,仅此而已。

因此,您调用string.Join将绑定(bind)到需要 params object[] 的重载.从方法的角度来看,object[]只有一个元素,即 IEnumerable , 所以它调用 ToString()就此返回。

您可能想要转换 IEnumerableIEnumerable<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/

相关文章:

c# - 如何阻止其他域指向我的域?

c# - SelectedItem 更改文本 block 变量

c# - LINQ group by property 作为参数

c# - CS8176 : Iterators cannot have by-reference locals

c# - 在 Azure 中创建表时出现异常

c# - Crystal 报表登录失败问题

c# - 在 Windows 通用应用程序中获取设备/操作系统版本和国家/语言代码

c# - 未执行 C# 中的垃圾收集。为什么?

c# - Convert.ToBase64String/Convert.FromBase64String 和 Encoding.UTF8.GetBytes/Encoding.UTF8.GetString 的区别

c# - 当前上下文用户控件中不存在名称 'xxx'