我如何 String.Join 盒装数组?

How do I String.Join a boxed array?

给定一个可能包含数组的 object(例如 int[]),如何调用正确的 IEnumerable<T> String.Join 重载?

var a = new []{1,2,3};
object o = a;

String.Join(",", a); // "1,2,3"
String.Join(",", o); // "System.Int32[]"

我希望 o 上的 String.Join 是数组的内容,而不是类型名称。


下面的完整上下文和尝试

我有一个 object 可以包含任何东西,包括各种 IEnumerable<T> 和数组,例如Int32[]。我有一种方法可以根据类型将其转换为适当的字符串:

private string ResultToString(object result)
{
    return result switch
    {
        string res => res,
        IEnumerable<object> enumerable => String.Join(", ", enumerable),
        null => "*null*",
        _ => result.ToString()
    };
}

目前,如果 result 是一个 int[],它会落入默认大小写。

您可以转换为 IEnumerable,然后使用 Cast<T>,它总是会成功 Object:

private string ResultToString(object result)
{
    IEnumerable enumerable = result as IEnumerable;
    if(enumerable == null) return result?.ToString();
    return string.Join(", ", enumerable.Cast<object>());
}

这会调用 this String.Join 重载。备注:

Join<T>(String, IEnumerable<T>) is a convenience method that lets you concatenate each member of an IEnumerable collection without first converting them to strings. The string representation of each object in the IEnumerable collection is derived by calling that object's ToString method.