Access List from another class

2019-01-18 15:09发布

问题:

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

回答1:

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...
    }
}


回答2:

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.



回答3:

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();
    }
}