【问题标题】:Why string.Join(string delimiter, IEnumerable collection) returns string with only 1 value [closed]为什么 string.Join(string delimiter, IEnumerable collection) 返回只有 1 个值的字符串 [关闭]
【发布时间】:2018-02-26 10:53:19
【问题描述】:

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

当我尝试将转换为 IEnumerable(非泛型)的数组传递给 string.Join 时,它只返回 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(string pattern, IEnumerable collection) 只返回 1 个值?

【问题讨论】:

  • returns only 1 value - 值是多少?你在期待什么?
  • 您能否详细说明您正在尝试做的事情,即预期结果?
  • 如果您从未填写或使用过list is IEnumerable,那么测试它的意义何在?
  • 你正在传递一个SportEvent[] - string.join 期待一个string[]
  • 所以如果listIEnumerable 你在array 上调用string.Join - 只有我会被这个混淆吗?

标签: c# arrays string ienumerable


【解决方案1】:

当我尝试将转换为 IEnumerable(非通用)的数组传递给 string.Join,结果只返回 1 个值。

在您提供的示例中,您没有将IEnumerable 传递给Join 方法,而是传递SportEvent 对象的数组。请注意,Join 方法对 objectIEnumerable&lt;T&gt; 都有重载。

问题是:为什么是string.Join(string pattern, IEnumerable collection) 只返回 1 个值?

因为Join 旨在返回单个值,该值是由分隔符分隔的每个数组元素的字符串表示形式的串联。

我会将各种集合传递给方法,我只是在测试 与代码。因此,我不想绑定到单个类型。一世 只会使用 StringBuilder 手动附加值。

如果我正确地解释了您的要求,并且您的目标是获取所有对象的字符串表示形式,而与它们的类型无关,那么您可以在基类中重写 toString 方法,如果需要,在派生类中重写,因为 @ 987654332@ 方法隐式调用每个元素的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);

【讨论】:

  • 是的,我确实覆盖了他们的 .ToString 方法。
猜你喜欢
  • 2014-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多