1

有没有办法用 List.Clear(); 来快速清除所有列表项?他们每个人的方法?因为当我第一次单击按钮时,我在列表中存储了一些项目,而当我第二次单击按钮时,它假设会获取新项目,但它仍然保留旧项目而不是新项目...我想清除所有列表在单击按钮并开始在我的列表中存储项目后立即帮助我解决这个问题......

我有以下课程:

Fruits
vegetables
cars
Homes
.
.
.
4

2 回答 2

2

The solution to your problem is simply to not have the lists in the first place.

Rather than having these static methods be void and sticking their results in static lists that need to be cleared each time they are called, you should instead have then return their values, like so:

public static List<string> GetFruits()
{   
    var list = new List<string>();

    OracleConnection conn1 = MyConnection.GetSourceConnection();

    conn1.Open();  
    using (OracleCommand storeFruits = new OracleCommand("MyCOMMAND", conn1))
    {
        using (OracleDataReader reader = storeFruits.ExecuteReader())
        {
            while (reader.Read())
            {
                list.Add((string)reader["TABLE_NAME"]);
            }
        }
    }

    return list;
}

This has a number of advantages:

  1. You can call the method concurrently without any concerns, since each caller has their own list.

  2. There is no worry about clearing the lists, ever. You start fresh every time.

  3. There is no worry about a list that one caller is using being modified as a result of some other call in some other location. Each caller only needs to worry about their code, not everyone else's.

于 2013-09-13T15:16:15.433 回答
0

如果它们都是私人列表,您将无法从其他班级看到它们

即使您制作了它们public static,您仍然必须这样做:

Class1.myLIST1.Clear();
Class2.myLIST2.Clear();
// etc
于 2013-09-13T14:50:35.693 回答