使用HashTable映射对象引用
时间:2020-03-06 15:03:21 来源:igfitidea点击:
我想使用HashTable将引用映射到对象而不是对象值
configMapping.Add("HEADERS_PATH", Me.headers_path)
这样,当我要检索" HEADERS_PATH"的值时,便可以为Me.headers_path分配一个值
类似于C中的"&"运算符
解决方案
使headers_path为适当(已设置)
我假设Me.headers_path是System.String。因为System.String是不可变的,所以我们无法实现所需的功能。但是我们可以添加一个间接级别,以实现类似的行为。
All problems in computer science can be solved by another level of indirection. Butler Lampson
C语言中的示例(请友好地编辑到VB中,并在以后删除此注释):
public class Holder<T> { public T Value { get; set; } } ... Holder<String> headerPath = new Holder<String>() { Value = "this is a test" }; configMapping.Add("HEADERS_PATH", headerPath); ... ((Holder<String>)configMapping["HEADERS_PATH"]).Value = "this is a new test"; // headerPath.Value == "this is a new test"
这似乎是一个字典,如果要更新的引用始终是字符串,则在.Net 2.0中可以将其定义为"字典",如果要获取任意引用,则可以将其定义为"字典"(不推荐)。
如果我们需要替换字典中的值,则可以定义自己的类,并提供一些帮助程序方法来简化此过程。
我不确定我们要做什么。假设smink是正确的,那么这里是他的代码的VB翻译。抱歉,我无法编辑它,我认为我的代表还不够。
public class Holder(Of T) public Value as T end class ... Dim headerPath as new Holder(Of String) headerPath.Value = "this is a test" configMapping.Add("HEADERS_PATH", headerPath) ... Directcast(configMapping["HEADERS_PATH"]),Holder(Of String)).Value = "this is a new test" 'headerPath.Value now equals "this is a new test"
@marcj,我们需要在答案中使用尖括号,因此将<用于<和<>用于>。再次抱歉,我不能只为我们编辑信息。