2

我正在做我在大学以外的第一个项目。我有两节课。在第一个中,我有一个将字符串添加到数组列表的方法。在第二个类中,我想从前一个类中的方法访问 arrayList,并获取它的元素。

我怎么能那样做?谢谢你的帮忙。

4

4 回答 4

0

您可以将 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

于 2012-08-24T09:40:49.593 回答
0

除非您使用的是 .NET 1.1,否则我会避免ArrayLists使用它们的强类型对应物List<T>

您需要public在类 1 中创建该方法。然后您可以从类 2 访问它(如果是,static或者如果您有类 1 的实例)。

例如:

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
        }
    }
}
于 2012-08-24T09:42:33.140 回答
0

最好的选择是使用一个只读属性来公开数组列表,如下所示:

class MyClass
{
    private ArrayList FArrayList;
    public ArrayList ArrayList { get { return FArrayList; } }

    ...
于 2012-08-24T09:44:59.423 回答
0

试试这个..

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.
    }
}
于 2012-08-24T09:55:39.107 回答