C#中如何向对象数组添加新对象?解决索引越界异常
问题:向数组中添加元素时触发IndexOutOfRangeException异常
类定义
public class LiveData { public string? serverTime { get; set; } public string? msgId { get; set; } public string? status { get; set; } public string? statusMessage { get; set; } public Data[] data {get; set} } public class Data { [Required] public DateTime Date { get; set; } public string Description{ get; set;} }
尝试向Data数组添加新元素时,使用了以下代码:
//get length of array int arrayLength= liveData.data.Length; liveData.data[arrayLength]= new LiveData { Date = DateTime.Now, Description = "New value" }
执行时抛出异常:System.IndexOutOfRangeException: Index was outside the bounds of the array.
正确实现方式
C#中的数组是固定长度的,创建后无法直接扩容,直接访问等于数组长度的索引必然越界(数组索引从0开始,最大索引为长度-1)。此外你代码里还犯了一个错误:实例化了LiveData而非Data类型,这会导致类型不匹配问题。
推荐两种解决方法:
方法1:转换为List操作(更简便)
List
// 将数组转换为List var dataList = liveData.data.ToList(); // 添加新的Data元素 dataList.Add(new Data { Date = DateTime.Now, Description = "New value" }); // 再将List转换回数组赋值给原对象 liveData.data = dataList.ToArray();
方法2:手动创建新数组(适合性能敏感场景)
如果不想引入List,可以手动创建一个长度+1的新数组,复制原数组元素后再添加新元素:
int originalLength = liveData.data.Length; // 创建长度比原数组大1的新数组 Data[] newDataArray = new Data[originalLength + 1]; // 复制原数组的所有元素到新数组 Array.Copy(liveData.data, newDataArray, originalLength); // 添加新元素到新数组的最后一位 newDataArray[originalLength] = new Data { Date = DateTime.Now, Description = "New value" }; // 替换原数组 liveData.data = newDataArray;
额外建议
如果你的场景需要频繁添加/删除元素,建议直接将LiveData类中的data字段定义为List<Data>而非数组,这样后续操作会更高效:
public class LiveData { public string? serverTime { get; set; } public string? msgId { get; set; } public string? status { get; set; } public string? statusMessage { get; set; } // 直接用List<Data>替代数组 public List<Data> data { get; set; } = new List<Data>(); }
之后添加元素只需直接调用liveData.data.Add(new Data { ... })即可。
内容的提问来源于stack exchange,提问作者Prasad Gavande
相关产品推荐
相关产品推荐

