【问题标题】:目标数组不够长。检查 destIndex 和长度,以及数组的下限。?
【发布时间】:2022-01-23 11:16:46
【问题描述】:

目标数组不够长。检查 destIndex 和长度,以及数组的下限

我该如何解决? 添加 Array.Copy 后发生此错误

我不知道......

static byte[] sendData = new byte[5];
  static int sendCount = 0;
    
    try
                        {
    
                            Console.Write("->");
                            string text = Console.ReadLine();
                            foreach(string s in text.Split(' '))
                            {
                                if(null != s && "" != s)
                                {
                                    sendData[sendCount++] = Convert.ToByte(s, 16);
                                }
                            }
                            byte[] LRC = new byte[1];
                            LRC = BitConverter.GetBytes((Int16)sendData[2] ^ sendData[3] ^ sendData[4]);
    
                            byte[] hexData = new byte[sendData.Length + LRC.Length];
                            Array.Copy(sendData, 0, hexData, 0, 5);//<-error occur this point
                            Array.Copy(LRC, 0, hexData, hexData.Length + 1, 1);//<-or this point
    
                            port.Write(hexData, 0, hexData.Length);
    
                            Array.Clear(sendData, 0, sendData.Length);
                            Array.Clear(LRC, 0, LRC.Length);
                            Array.Clear(hexData, 0, hexData.Length);
                            sendCount = 0;
                        }
                        catch(Exception e)
                        {
                            Console.WriteLine(e.Message);
                            Console.WriteLine("Check Data");
                        }

【问题讨论】:

  • 您在代码中做错了太多事情...
  • @Dai 学C#的时间不长,估计有很多错误。我需要更加努力学习.....

标签: c# arrays


【解决方案1】:

回答具体问题,复制方法的定义:

public static void Copy (
    Array sourceArray, int sourceIndex,
    Array destinationArray, int destinationIndex,
    int length);

你的情况

Array.Copy(LRC, 0, hexData, hexData.Length + 1, 1);

因此,您正在尝试将字节复制到数组hexData 到索引hexData.Length + 1,这基本上超出了它的边界。

我不知道您要实现什么,但您应该确保复制期间的目标索引小于或等于hexData.Length - 1(还要考虑长度)。

【讨论】:

  • 学C#的时间不长,估计有很多错误。我需要更加努力地学习......谢谢你的回答! :)
猜你喜欢
  • 2016-04-08
  • 1970-01-01
  • 2019-09-12
  • 1970-01-01
  • 2020-03-16
  • 2020-01-07
  • 2013-08-29
  • 2012-05-08
  • 2012-08-02
相关资源
最近更新 更多