是否可以在 C# 方法中引用先前的参数作为参数默认值?

Is it possible to reference previous parameter as parameter default value in a C# method?

我打算编写一个 C# 扩展方法来仅连接字符串数组的特定范围的元素。例如,如果我有这个数组:

+-----+  +-----+  +-------+  +------+  +------+  +-----+
| one |  | two |  | three |  | four |  | five |  | six |
+-----+  +-----+  +-------+  +------+  +------+  +-----+
   0        1         2          3         4        5

我只想使用 从索引 2 到索引 4 加入他们。我得到了 three,four,five。 如果用户不提供开始索引和结束索引,那么我的 Join 方法将连接所有数组元素。下面是我的方法签名。

public static class StringSplitterJoinner
{
    public static string Join(this string[] me, string separator, int start_index = 0, int end_index = me.Length - 1) {

    }
}

问题是参数 end_index 无法引用第一个参数 me,它会产生错误。我不希望用户总是提供 start_indexend_index 我希望我的方法有一些有意义的默认值。在这种情况下,我该如何解决这个问题?

我建议使用重载:

public static string Join(this string[] me, string separator) {
  //TODO: add parameters' validation

  return Join(me, separator, 0, me.Length - 1);
}

public static string Join(this string[] me, string separator, int start_index) {
  //TODO: add parameters' validation

  return Join(me, separator, start_index, me.Length - 1);
}

public static string Join(this string[] me, string separator, int start_index, int end_Index) {
  //TODO: implement logic here
}

这个怎么样:

public static class StringSplitterJoinner
{
    public static string Join(this string[] me, string separator, int start_index = 0, int? end_index = null)
    {
        if (!end_index.HasValue) end_index = me.Length - 1;
    }
}

您也可以这样做:

public static string Join<T>(this IReadOnlyCollection<T> me,
  string separator, int startIndex = 0, int endIndexInclusive = -1)
{
  if (endIndexInclusive < 0)
    endIndexInclusive += me.Count;

  var range = me.Skip(startIndex).Take(endIndexInclusive - startIndex + 1);
  return string.Join(separator, range);
}

这里的想法是 negative 索引从另一端开始计数,所以 -1 是最后一个索引,-2 是倒数第二个索引, 等等。如果未明确指定参数,则采用的值 -1 表示集合中的最后一个条目。

(如果需要,您也可以包括 if (startIndex < 0) startIndex += me.Count;。)

方法已经变得通用(generic),但仍然可以在 string[] 上使用。示例:

string[] myArray = ...
var joined = myArray.Join(",", 2, -3); // skips first two, and last two, entries

请注意,-3 也可以使用 bit-wise 补码写成 ~2。这样看起来比较对称,myArray.Join(",", 2, ~2).