按键获取哈希表 obj 并更改其 public 属性

Get hashtable obj by key & change its public properties

首先,我声明了一个哈希表及其值。哈希表条目的键是一个 GUID,值是一个包含一些字符串值的对象。

    Guid g = Guid.NewGuid();
    Hashtable hash = new Hashtable();
    InstallationFiles instFiles = new InstallationFiles(string1, string2, string3);
    hash.Add(g, instFiles);
    //...add many other values with different GUIDs...

我的目标是让用户能够编辑字符串 1、字符串 2、字符串 3。长话短说,我现在可以得到需要编辑的条目的 "GUID g":

   public void edit() 
   {
         //here I retrieve the GUID g of the item which has to be edited:
         object objectHash = item.Tag;
         //here i loop through all hash entries to find the editable one:
         foreach(DictionaryEntry de in hash)
         {
            if(de.Key.ToString() == objectHash) 
            {
            //here I would like to access the selected entry and change string1 - 
           //the line below is not working.

            hash[de.Key].string1 = "my new value"; 
            }
         }

   }

如何让这条线工作?

    hash[de.Key].string1 = "my new value"; 

使用Dictionary<Guid, InstallationFiles>代替HashTable

更新。你可以用这个。

 (hash[de.Key] as InstallationFiles).string1 = "asdasd" 

好的,说明:

因为 Hashtable 不是泛型类型,它包含对作为对象的键和值的引用。

这就是为什么当您访问您的值 hashtable[mykey] 时,您得到了对 Object 的引用。要使其成为您的类型 (InstallationFiles) 的参考,您必须从 "reference to Object" 获取 "reference to InstallationFiles"。在我的示例中,我使用“as”运算符来执行此操作。