【发布时间】:2011-04-12 15:14:11
【问题描述】:
谁能告诉我如何在一个类中创建一个列表并从另一个类中访问它?
【问题讨论】:
标签: c# list inheritance dictionary scope
谁能告诉我如何在一个类中创建一个列表并从另一个类中访问它?
【问题讨论】:
标签: c# list inheritance dictionary scope
public class MyClass {
private List<string> myList = new List<string>();
public List<string> GetList()
{
return myList;
}
}
你可以有任何东西而不是字符串。
现在您可以创建MyClass 的对象,并可以访问您已实现的公共方法以返回myList。
public class CallingClass {
MyClass myClass = new MyClass();
public void GetList()
{
List<string> calledList = myClass.GetList();
///More code here...
}
}
【讨论】:
要创建列表,请调用列表构造函数:
class Foo
{
private List<Item> myList = new List<Item>();
}
为了让其他类可以访问它,添加一个公开它的公共属性。
class Foo
{
private List<Item> myList = new List<Item();
public List<Item> MyList
{
get { return myList; }
}
}
要从另一个类访问列表,您需要引用Foo 类型的对象。假设你有这样一个引用,它被称为foo,那么你可以写foo.MyList来访问这个列表。
您可能要小心直接公开列表。如果您只需要允许只读访问,请考虑改为公开ReadOnlyCollection。
【讨论】:
如果您需要将 List 声明为静态属性
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();
}
}
【讨论】: