【问题标题】:C# equivalent to Java's Arrays.fill() method [duplicate]C# 等效于 Java 的 Arrays.fill() 方法[重复]
【发布时间】:2011-10-13 06:39:53
【问题描述】:

我在 Java 中使用以下语句:

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

请建议 C# 等效项。

【问题讨论】:

标签: c# java arrays


【解决方案1】:

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

// Note: start is inclusive, end is exclusive (as is conventional
// in computer science)
public static void Fill<T>(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>(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;
    }
}

【讨论】:

  • 我希望我的编辑是合理的.. 或者将变量命名为uptoIndex
  • @nawfal:不,它是故意(尽管并非始终如一)排他性的。我已经整理并添加了一个替代方案。
  • 乔恩,你为什么要检查异常情况并在 clr 这样做时扔掉自己?我对这种设计有点困惑。仅第二个条件检查(在您的两个示例中)就足够了吗?
  • @nawfal:CLR 会抛出不同的异常。鉴于这些是方法参数,抛出的异常应该是 ArgumentExceptions,IMO。这表明是调用代码有问题,而不是方法本身的问题。
  • @JonSkeet,有点太晚了......仍然是一个想法:负数不会导致循环中的异常......抛出负数或反转启动和停止需要有充分的理由......
【解决方案2】:

您似乎想做更多这样的事情

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);

【讨论】:

    【解决方案3】:

    这样试试

    Array.Copy(source, target, 5);
    

    更多信息here

    【讨论】:

    • 这与fill 的作用不同。
    • 但它不是要复制的目标数组...它正在占用长度..mynewArray 是 int[]
    • Rasel 的建议没问题。工作示例: int[] arr=new int[1000]; Array.Copy(arr.Select (i => 5).ToArray(),arr, arr.Length);
    猜你喜欢
    • 2012-10-06
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 2012-01-16
    • 2016-05-17
    • 2014-09-21
    • 2011-03-18
    • 1970-01-01
    相关资源
    最近更新 更多