开发者

Access List from another class

开发者_JS百科can anyone tell me how to create a list in one class and access it from another?


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


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜