Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
调用构造函数类的C#ArrayList_C#_.net_Constructor_Arraylist - Fatal编程技术网

调用构造函数类的C#ArrayList

调用构造函数类的C#ArrayList,c#,.net,constructor,arraylist,C#,.net,Constructor,Arraylist,我知道ArrayList可能不是处理这种特殊情况的方法,但请幽默我,帮助我摆脱这种头痛 我有一个构造函数类,如下所示: class Peoples { public string LastName; public string FirstName; public Peoples(string lastName, string firstName) { LastName = lastName;

我知道ArrayList可能不是处理这种特殊情况的方法,但请幽默我,帮助我摆脱这种头痛

我有一个构造函数类,如下所示:

class Peoples
    {
        public string LastName;
        public string FirstName;
        public Peoples(string lastName, string firstName)
        {
            LastName = lastName;
            FirstName = firstName;
        }
    }
我试图通过调用这个构造函数来构建一个ArrayList来构建一个集合。然而,当我使用这个构造函数时,我似乎找不到正确构建ArrayList的方法。我用数组解决了这个问题,但没有数组列表

我一直在尝试构建我的ArrayList:

ArrayList people = new ArrayList();
            people[0] = new Peoples("Bar", "Foo");
            people[1] = new Peoples("Quirk", "Baz");
            people[2] = new Peopls("Get", "Gad");
根据我得到的异常,我的索引显然超出了范围。

应该是:

people.Add(new Peoples(etc.));
而不是

people[0] = new people()...;
或者更好:

List<People> people = new List<People>();

people.Add(new People);

您应该向列表中添加元素。像下面这样

ArrayList people = new ArrayList(); 
people.Add(new Peoples("Bar", "Foo"));
您应该使用函数添加到数组列表中

ArrayList peoplesArray = new ArrayList();
peoplesArray.Add(new Peoples("John","Smith");
你需要做什么

people.Add (new Peoples("Bar", "Foo"));
people.Add (new Peoples("Quirk", "Baz"));
people.Add (new Peoples("Get", "Gad"));

尝试
people。添加(新的people(“Bar”、“Foo”);

当您尝试调用people[i]而不首先填充数组列表时,您将获得IndexAutoFrangeException。您必须首先添加到ArrayList

ArrayList list = new ArrayList();
list.Add(new Peoples("Bar", "Foo"));
然后,您可以通过索引访问列表,这将在foreach或for循环中完成

您不使用将为您提供强类型集合的
列表
有什么原因吗?
另外,虽然我意识到你可能只是为这个问题编写了代码,但你在课堂上有公开访问的字段。

供参考,ArrayList被许多人认为是邪恶的。正如Kevin所说,最好让我们列出它

这个列表就是所谓的泛型。谷歌的“强类型”、“装箱”和“泛型”可以更好地理解为什么

回到你原来的问题: 数组的大小必须在实例化时声明,即。 人[]人=新人[5]

这将在数组中创建5个空单元格,因此您可以使用下标来访问这些单元格,即[0]

当使用默认构造函数实例化时,ArrayList或List没有单元格,即。 列表人员=新列表()

此时不存在人员[0]

使用people.Add(new people(“first”、“last”);将新单元格添加到列表中。现在下标[0]有效,但[1]仍然无效,因为只有一个单元格


列表(即ArrayList或list)可以使用.Add()动态增长。添加到列表后,可以使用下标[i]引用它们,但您不能使用子脚本添加它们。

太好了,谢谢!很抱歉,我还没有完全弄清楚如何设置我的帖子的格式。如果有人能给我发送一条带有一些提示的消息,那就太好了。感谢帮助。这样做的唯一原因是,这是一个学校项目,我需要经历所有不同的过程类型(数组、数组列表、列表等)。但我非常感谢关于更好的方法的提示。同时,您的it可以改变人与人之间的关系。
ArrayList list = new ArrayList();
list.Add(new Peoples("Bar", "Foo"));