可以在已经实例化的对象[]数组中添加额外的元素吗?

huangapple go评论54阅读模式
英文:

Is it possible to add an extra element to an object[] array if it has already been instantiated?

问题

假设以下代码是一个示例:

static void Main(string[] args)
{
    Object objects = new Object();
    objects.object1 = new ObjectList[4];
}

public class Object
{
    public ObjectList[] object1;
}

public class ObjectList
{
    public string name;
}

假设用户希望稍后使用 Console.ReadLine()object1[] 数组中添加另一个元素 - 这是否可能,或者初始化后数组长度是最终的?换句话说,是否可以删除或覆盖相同的对象数组,以包含5个元素而不是4个(可能利用临时数组来传输数组中的不同对象)?

英文:

Assume the following code as an example:

static void Main(string[] args)
    {
        Object objects = new Object();
        objects.object1 = new ObjectList[4];
    }
    
    public class Object
    {
        public ObjectList[] object1;
    }
    
    public class ObjectList
    {
        public string name;
    }

Let's say the user wants to input another element in the object1[] array later on with a Console.ReadLine() - would this be possible or is the array length after initialization final? In other words, can the same object array be deleted or overwritten to contain 5 elements instead of 4 (perhaps utilizing a temporary array to transfer the separate objects within the array).

答案1

得分: 1

是的,但不是。虽然你可以调整数组的大小并将所有元素复制到其中,但这不是应该的做法,因为会导致性能问题,而且数组本来就是用来保存精确数量的元素的。

正确的做法之一是使用 List<T>,然后可以使用 LINQ 进行筛选、添加元素、删除元素,...

英文:

Yes, but no. Although you can resize the array and copy all the elements into it, thats not how it should be done, because of performance issues and simply because arrays are meant to hold exact ammount of elements.

One of correct ways of doing this is to use List<T> and from here you can filter it using LINQ, add elements, remove elements,...

答案2

得分: 0

Array.Resize(ref objects.object1, 5);

它调整你的数组大小(将元素从旧数组复制到新数组)。

英文:

Array.Resize(ref objects.object1, 5);

It resizes your array (copies elements from old one to new one).

huangapple
  • 本文由 发表于 2023年2月24日 04:04:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75549797.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定