为什么 string.Join(string delimiter, IEnumerable collection) returns string with only 1 value

Why string.Join(string delimiter, IEnumerable collection) returns string with only 1 value

我正在尝试创建一个方法,将任何 IEnumerable 转换为字符串(包括数组)。

当我尝试将转换为 IEnumerable(非通用)的数组传递给 string.Join 时,结果 returns 只有 1 个值。 IEnumerable 由各种 类 组成,它们派生自一个共同的祖先并将其 7 项正确传递给方法:

var list = new List<SportEvent>
var array = new SportEvent[]
            {
                new SportMatch(),
                new SportMatch(),
                new SportMatchBase(),
                new SportMatch(),
                new SportEvent(),
                new SportEvent(),
                new SportEvent(),
            };

            bool isImplementingIEnumerable = list is IEnumerable;

if (isImplementingIEnumerable)
   {
      valueRepresentation = string.Join(", ", (IEnumerable)array);
   }

我将此代码用作概念证明。我会将各种集合传递给该方法,我只是用代码进行测试。因此,我不想绑定到单个类型。我将使用 StringBuilder 手动附加值。

问题是:为什么 string.Join(字符串模式,IEnumerable 集合)returns 只有 1 个值?

When I try to pass array casted as an IEnumerable (not generic) to string.Join, it returns only 1 value as a result.

在您提供的示例中,您没有将 IEnumerable 传递给 Join 方法,而是传递了一个 SportEvent 对象数组。请注意 Join 方法对 object and IEnumerable<T>.

都有重载

Question is: Why string.Join(string pattern, IEnumerable collection) returns only 1 value?

因为 Join 意味着 return 单个值,它是由分隔符分隔的每个数组元素的字符串表示形式的串联。

I will pass various collections to the method and I'm just testing with the code. Therefore, I do not want to bind to a single Type. I will just manually append values with StringBuilder.

如果我正确解释了您的要求,并且您的目标是独立于对象的类型获得所有对象的字符串表示,那么您可以重写基础 class 中的 toString 方法,并且,如有必要,在派生的 classes 中,因为 Join 方法隐式调用每个元素的 toString 方法,例如:

class SportMatchBase
{
    public string Name { get; set; }

    public override string ToString()
    {
        return this.Name;
    }
}

class SportEvent : SportMatchBase
{
    public DateTime Date { get; set; }

    public override string ToString()
    {
        return $"{Name} ({Date.ToShortDateString()})";
    }
}

var array = new SportMatchBase[]
{
    new SportMatchBase() { Name = "Sport match" },
    new SportEvent() { Name = "Sport event", Date = DateTime.Now }
};

string valueRepresentation = string.Join<SportMatchBase>(", ", array);