Initializing lists in a constructor

∥☆過路亽.° 提交于 2020-01-13 05:58:04

问题


I need to create a class that also initializes two event lists to new empty lists. I'm not sure if that is what is being asked of me, but I know how to create a list and how to create a constructor. I created 2 lists, and now I should create the constructor. Here is one of my lists:

List<Person> organize = new List<Person>();

How do I initialize the two event lists in the constructor to new lists?


回答1:


Based on what I can gather from your question, you have a class with two Lists.

Your requirements say that inside your class, you need to initialize the Lists to empty lists.

Below is the example (the only difference is that I never initialize the Lists when they declared, but in the class constructor instead):

public class YourClass
{
    List<Person> organize;
    List<Person> anotherOrganize;

    // constructor
    public YourClass()
    {
        // initialize the two lists to empty lists
        organize = new List<Person>();
        anotherOrganize = new List<Person>();
    }
}



回答2:


If your list is declared as a field (member variable directly inside the class) and it's initialized at its declaration, you shouldn't to reinitialize it in the constructor. The initialization expression will get moved to the constructor by the compiler automatically.




回答3:


If this is homework, your instructor is probably telling you to initialize the lists inside of the constructor instead of at the declaration point.

class MyClass
{
    List<Person> organize;

    public MyClass()
    {
        this.organize = new List<Person>();
    }
}



回答4:


List<Person> organize = new List<Person>();

This will create an empty list. Can you be more specific? I feel like some details are missing.

Perhaps you mean something like this?

 public class TestClass
 {
      List<Person> personList;

      public TestClass()
      {
           personList = new List<Person>();
      }

 }



回答5:


I think what you're asking is why the constructor to your class should instantiate the two lists (?). You're right that

List<Person> organize = new List<Person>();

will instantiate the list. But so will:

List<Person> organize;
public MyClass()
{
organize = new List<Person>();
}

Am I understanding the question?



来源:https://stackoverflow.com/questions/2495685/initializing-lists-in-a-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!