Dat*_*ase 2 c# hashtable arraylist
我想要一个包含HashTables的ArrayList.我创建了一个Hashtable并添加了值.然后我将它添加到ArrayList.然后我更改了Hashtables的值并再次添加了Array List.它不会保存第一个值并结束具有与上一个值完全相同的重复值!
有什么建议?这是我的代码
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
将开始移动到Main函数内部,然后重新初始化它以进行第二次添加(并使用@lasseespeholt表示使用List<T>).
static List<Hashtable> StartList = new List<Hashtable>();
static void Main(string[] args)
{
Hashtable Start = new Hashtable();
Start["active"] = true;
Start["name"] = "prog1";
Start["path"] = @"C:\programfiles\prog1";
Start["parameter"] = string.Empty;
StartList.Add(Start);
Start = new Hashtable();
Start["active"] = false;
Start["name"] = "prog2";
Start["path"] = @"C:\programfiles\prog2";
Start["parameter"] = "/q";
StartList.Add(Start);
Run Code Online (Sandbox Code Playgroud)
您正在修改唯一的 Start Hashtable对象,您必须创建一个新对象:
Start = new Hashtable();
在第一个之后:
StartList.Add(Start);
请记住,您只是将对象的引用添加到ArrayList:所以您的代码所做的是:填充哈希表,将其引用添加到列表中,再修改一次,然后再次添加相同的引用.
想补充一下,你为什么要使用哈希表?使用你想要的字段的新类会好得多 - 然后他们可以有一个PrintInfo或一个ToString覆盖来获取你需要的信息 - 并且可能是一种Execute方法.