通过键&获取哈希表obj改变其公共财产 [英] Get hashtable obj by key & change its public properties
问题描述
首先,我声明一个哈希表及其值.哈希表条目的键是GUID,值是带有几个字符串值的对象.
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...
我的目标是使用户可以编辑字符串1,字符串2,字符串3.简而言之,我处于可以编辑该条目的"GUID g"的位置:
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";
推荐答案
使用 Dictionary< Guid,InstallationFiles>
代替 HashTable
upd.您可以使用它.
upd. You can use this.
(hash[de.Key] as InstallationFiles).string1 = "asdasd"
好,解释:
因为哈希表不是通用类型,所以它包含对键和值的引用作为对象.
Because Hashtable is not generic type, it contains references on keys and values as Objects.
这就是为什么当您访问值 hashtable [mykey]
时,您引用了 Object
.要使其成为对您的类型( InstallationFiles
)的引用,您必须从对 Object
的引用"获得对 InstallationFiles
的引用".在我的示例中,我使用" as
"运算符执行此操作.
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.
这篇关于通过键&获取哈希表obj改变其公共财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!