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

Jus*_*ner 4 c# methods extension-methods parameter-passing

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

+-----+  +-----+  +-------+  +------+  +------+  +-----+
| one |  | two |  | three |  | four |  | five |  | six |
+-----+  +-----+  +-------+  +------+  +------+  +-----+
   0        1         2          3         4        5
Run Code Online (Sandbox Code Playgroud)

而且我只想使用,索引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) {

    }
}
Run Code Online (Sandbox Code Playgroud)

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

Dmi*_*nko 6

我建议使用重载

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
}
Run Code Online (Sandbox Code Playgroud)