有没有办法用 List.Clear(); 来快速清除所有列表项?他们每个人的方法?因为当我第一次单击按钮时,我在列表中存储了一些项目,而当我第二次单击按钮时,它假设会获取新项目,但它仍然保留旧项目而不是新项目...我想清除所有列表在单击按钮并开始在我的列表中存储项目后立即帮助我解决这个问题......
我有以下课程:
Fruits
vegetables
cars
Homes
.
.
.
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:
You can call the method concurrently without any concerns, since each caller has their own list.
There is no worry about clearing the lists, ever. You start fresh every time.
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.
如果它们都是私人列表,您将无法从其他班级看到它们
即使您制作了它们public static
,您仍然必须这样做:
Class1.myLIST1.Clear();
Class2.myLIST2.Clear();
// etc