Access List from another class

后端 未结 3 1814
不知归路
不知归路 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:27

    In case you need a List declared as static property

    class ListShare 
    {
        public static List<String> DataList { get; set; } = new List<String>();
    }
    
    class ListUse
    {
        public void AddData()
        {
            ListShare.DataList.Add("content ...");
        }
    
        public void ClearData()
        {
            ListShare.DataList.Clear();
        }
    }
    
    0 讨论(0)
  • 2020-12-09 06:28

    To create a list call the list constructor:

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

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

    class Foo
    {
        private List<Item> myList = new List<Item();
    
        public List<Item> 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.

    0 讨论(0)
  • 2020-12-09 06:46
    public class MyClass {
    
        private List<string> myList = new List<string>();
    
        public List<string> GetList()
        {
            return myList;
        }
    } 
    

    You can have any anything there instead of string. Now you can make an object of MyClass and can access the public method where you have implemented to return myList.

    public class CallingClass {
    
        MyClass myClass = new MyClass();
    
        public void GetList()
        {
            List<string> calledList = myClass.GetList();
            ///More code here...
        }
    }
    
    0 讨论(0)
提交回复
热议问题