Get hashtable obj by key & change its public properties

允我心安 提交于 2021-01-28 18:54:30

问题


First of all I declare a hashtable and its values. The key of a hashtable entry is a GUID and the value is an object with a few string values.

    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...

My goal is to give a user a possibility to EDIT string 1, string2, string3. To cut a long story short, I am in a position where I can get the "GUID g" of the entry which needs to be edited:

   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"; 
            }
         }

   }

How do I make this line work?

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

回答1:


Use Dictionary<Guid, InstallationFiles> instead HashTable

upd. You can use this.

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

Ok, explanation:

Because Hashtable is not generic type, it contains references on keys and values as Objects.

Thats why, when you access to your value hashtable[mykey], you got reference to Object. To make it as reference to your type (InstallationFiles), you have to from "reference to Object" get "reference to InstallationFiles". Im my sample I use "as" operator to do this.



来源:https://stackoverflow.com/questions/39855224/get-hashtable-obj-by-key-change-its-public-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!