[英]Accessing An ArrayList from a method in a different class
我正在大學外進行我的第一個項目。 我有兩節課。 在第一個中,我有一種將字符串添加到arraylist的方法。 在第二個類中,我想從上一個類中的方法訪問arrayList,並獲取它的元素。
我該怎么辦? 感謝您的幫助。
您可以在第一個類中將ArrayList公開為靜態屬性,然后可以從第二個類中訪問該屬性。
public class First
{
public static ArrayList MyList { get; set; }
}
public class Second
{
public void SomeMethod()
{
//First.ArrayList will give you access to that class
}
}
最好不要使用ArrayList (如果使用的是.Net 2.0或更高版本),請使用安全類型的List
除非您使用.NET 1.1,否則我將避免使用ArrayLists
並使用其強類型對應項List<T>
。
您需要將該方法在類1中public
。然后,如果該方法是static
或具有類1的實例,則可以從類2訪問該方法。
例如:
public class Class1{
public List<String> getList()
{
// create the list and return it
}
}
public class Class2{
Class1 firstClass{ get;set; }
void foo()
{
// now you can access the List<String> of class1 via it's instance
List<String> list = firstClass.getList();
foreach(String s in list)
{
// do something
}
}
}
最好的選擇是使用一個只讀屬性,該屬性公開數組列表,如下所示:
class MyClass
{
private ArrayList FArrayList;
public ArrayList ArrayList { get { return FArrayList; } }
...
嘗試這個..
public class First
{
public ArrayList MyList;
public First()
{
MyList = new ArrayList();
}
public void AddString(string str)
{
MyList.Add(str);
}
}
public class Second
{
public void someMethod()
{
First f = new First();
f.AddString("test1");
f.AddString("test2");
f.AddString("test3");
ArrayList aL = f.MyList; // you will get updated array list object here.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.