【问题标题】:How to implement Array.Copy in C#如何在 C# 中实现 Array.Copy
【发布时间】:2020-12-06 12:05:10
【问题描述】:

我需要在一个函数中实现 Array.Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)。

它得到的数组是一个 char[] 数组,这是我的实现,但它不起作用:

private char[] ArrayCopier(char[] chars, int startIndex, int length)
        {
            char[] NewArray = new char[length];
            int index = 0;

            for (int i = startIndex; i < length; i++)
            {
                NewArray[index] = chars[i];
            }

            return NewArray;
        }

【问题讨论】:

  • 您忘记增加index 计数器。
  • @DavidPivovar 啊谢谢,但还是不行:(
  • 还有i &lt; (length + startIndex)

标签: c# arrays copy


【解决方案1】:

在你的 for 循环中,你需要 index++;否则它将把每个字符放在新数组的第一个位置。

我还会检查您是否超出了源数组的范围。

所以:

private char[] ArrayCopier(char[] chars, int startIndex, int length)
        {
            char[] NewArray = new char[length];
            int index = 0;

            for (int i = startIndex; (i < length)&&(i<chars.length); i++)
            {
                NewArray[index] = chars[i];
                index++;

            }

            return NewArray;
        }

【讨论】:

    【解决方案2】:

    这应该可以解决您的问题:

    private char[] ArrayCopier(char[] chars, int startIndex, int length)
    {
        // make sure startIndex is within the bounds of the given array
        if (startIndex < 0 || startIndex >= chars.Length)
            throw new IndexOutOfRangeException();
    
        // if necessary, recalculate length to be within the array boundaries
        if (startIndex + length > chars.Length)
            length = chars.Length - startIndex;
    
        var result = new char[length];
    
        for (int i = 0; i < length; i++)
            result[i] = chars[i + startIndex];
    
        return result;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-13
      • 2021-08-18
      • 2010-09-28
      • 2016-04-13
      • 2014-10-29
      • 2018-02-14
      • 2011-01-17
      相关资源
      最近更新 更多