【发布时间】:2011-03-25 18:44:49
【问题描述】:
我想要一个包含 HashTable 的 ArrayList。我创建了一个哈希表并添加了值。然后我将它添加到 ArrayList。然后我更改了哈希表的值并再次将其添加到数组列表中。它不保存第一个值,并以与最后一个值完全相同的重复值结尾!
有什么建议吗?这是我的代码
namespace ValuesTest
{
internal class Class1
{
public static ArrayList StartList = new ArrayList();
public static Hashtable Start = new Hashtable();
static void Main(string[] args)
{
Start["active"] = true;
Start["name"] = "prog1";
Start["path"] = @"C:\programfiles\prog1";
Start["parameter"] = string.Empty;
StartList.Add(Start);
Start["active"] = false;
Start["name"] = "prog2";
Start["path"] = @"C:\programfiles\prog2";
Start["parameter"] = "/q";
StartList.Add(Start);
foreach (Hashtable HT in StartList)
{
Console.WriteLine(HT["active"] + " - " + HT["name"] + " - " + HT["path"] + " - " + HT["parameter"]);
// it will always gives
// False - prog2 - C:\programfiles\prog2 - /q
}
Console.ReadLine();
}
}
}
【问题讨论】:
-
我最近看到了很多ArrayList。相反,您应该使用 List
,除非您使用的是 .Net 框架 1/1.1。 List 将提供更好的性能并避免强制转换('foreach' 在您的情况下是隐含的)。问候 -
您不会创建 Hashtable 的新实例,而是覆盖值。 P.S.:如果您期待答案,则在主题中使用多个感叹号并没有太大帮助:p
-
不过,人们应该对问题而不是语法进行投票。