C# 通过键获取哈希表obj&;更改其公共属性
首先,我声明一个哈希表及其值。哈希表项的键是GUID,值是具有几个字符串值的对象C# 通过键获取哈希表obj&;更改其公共属性,c#,hashtable,C#,Hashtable,首先,我声明一个哈希表及其值。哈希表项的键是GUID,值是具有几个字符串值的对象 Guid g = Guid.NewGuid(); Hashtable hash = new Hashtable(); InstallationFiles instFiles = new InstallationFiles(string1, string2, string3); hash.Add(g, instFiles); //...add many other 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...
我的目标是让用户能够编辑字符串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";
使用字典
代替哈希表
upd。你可以用这个
(hash[de.Key] as InstallationFiles).string1 = "asdasd"
好的,解释一下:
因为哈希表不是泛型类型,所以它包含对键和值的引用作为对象
这就是为什么当您访问值哈希表[mykey]
时,您会得到对对象的引用。要将其作为对您的类型(InstallationFiles
)的引用,您必须从“对对象的引用”中获取“对InstallationFiles
”的引用”。在我的示例中,我使用“作为
”操作符来执行此操作 使用字典
代替哈希表
upd。你可以用这个
(hash[de.Key] as InstallationFiles).string1 = "asdasd"
好的,解释一下:
因为哈希表不是泛型类型,所以它包含对键和值的引用作为对象
这就是为什么当您访问值哈希表[mykey]
时,您会得到对对象的引用。要将其作为对您的类型(InstallationFiles
)的引用,您必须从“对对象的引用”中获取“对InstallationFiles
”的引用”。在我的示例中,我使用“作为
”操作符来执行此操作 使用字典
获取强类型变量并访问其属性使用字典
获取强类型变量并访问其属性我的老板希望我使用哈希表。我根本无法使用哈希表?因此,(hash[de.Key]作为安装文件)。string1=“asdasd”
非常感谢。它起作用了。下次我会尽量用字典。虽然这肯定是个好建议,但它根本不是问题的答案。这是应该作为评论发布的内容。@Servy嗨,Servy。我更新了我的答案。希望它看起来像现在的答案。我的老板希望我使用哈希表。我根本无法使用哈希表?因此,(hash[de.Key]作为安装文件)。string1=“asdasd”
非常感谢。它起作用了。下次我会尽量用字典。虽然这肯定是个好建议,但它根本不是问题的答案。这是应该作为评论发布的内容。@Servy嗨,Servy。我更新了我的答案。希望它看起来像现在的答案。