C#相当于Java的Arrays.fill()方法

我在Java中使用以下语句:

Arrays.fill(mynewArray, oldArray.Length, size, -1); 

请建议等效的C#。

我不知道框架中有什么做到这一点,但它很容易实现:

 // Note: start is inclusive, end is exclusive (as is conventional // in computer science) public static void Fill(T[] array, int start, int end, T value) { if (array == null) { throw new ArgumentNullException("array"); } if (start < 0 || start >= end) { throw new ArgumentOutOfRangeException("fromIndex"); } if (end >= array.Length) { throw new ArgumentOutOfRangeException("toIndex"); } for (int i = start; i < end; i++) { array[i] = value; } } 

或者,如果要指定计数而不是开始/结束:

 public static void Fill(T[] array, int start, int count, T value) { if (array == null) { throw new ArgumentNullException("array"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (start + count >= array.Length) { throw new ArgumentOutOfRangeException("count"); } for (var i = start; i < start + count; i++) { array[i] = value; } } 

试试这样吧

 Array.Copy(source, target, 5); 

有关更多信息,请访问

看起来你想做更像这样的事情

 int[] bar = new int[] { 1, 2, 3, 4, 5 }; int newSize = 10; int[] foo = Enumerable.Range(0, newSize).Select(i => i < bar.Length ? bar[i] : -1).ToArray(); 

使用旧值创建一个新的更大的数组并填充额外的数组。

如需简单填写试试

 int[] foo = Enumerable.Range(0, 10).Select(i => -1).ToArray(); 

或子范围

 int[] foo = new int[10]; Enumerable.Range(5, 9).Select(i => foo[i] = -1);