Access List from another class

后端 未结 3 1831
不知归路
不知归路 2020-12-09 06:16

can anyone tell me how to create a list in one class and access it from another?

3条回答
  •  孤城傲影
    2020-12-09 06:28

    To create a list call the list constructor:

    class Foo
    {
        private List myList = new List();
    }
    

    To make it accessible to other classes add a public property which exposes it.

    class Foo
    {
        private List myList = new List MyList
        {
            get { return myList; }
        }
    }
    

    To access the list from another class you need to have a reference to an object of type Foo. Assuming that you have such a reference and it is called foo then you can write foo.MyList to access the list.

    You might want to be careful about exposing Lists directly. If you only need to allow read only access consider exposing a ReadOnlyCollection instead.

提交回复
热议问题