【发布时间】:2019-10-21 23:54:51
【问题描述】:
在将 perl 模块移植到 c# 代码时,我偶然发现了如何将多键哈希从 perl 移植到 c# 等效项:
$map{$key1}{$key2}=$value;
在要移植的 perl 代码中,我可以使用相同的 key1 定义多行,而且我只能使用第一个 key 访问哈希:
# define multiple lines with the same key1 : ex :
$key1 = '1';
$key2 = 'a';
$map{$key1}{$key2}=54;
$key2 = 'b';
$map{$key1}{$key2}=47;
# can access the hash only with the first key : ex :
if (exists($$map{'1'}) {}
但在 c# 中,如果我使用 c# 字典,我不能添加相同的 key1 行,它表示重复键。例如,在c#中,如果我这样做,我有一个错误:
var map = new Dictionary<string, Dictionary<string, int>>();
map.Add(key1, new Dictionary<string, int>() { { key2, 54 } });
map.Add(key1, new Dictionary<string, int>() { { key2, 47 } });
同样,如果我使用元组作为键,我将能够添加 2 行具有相同 key1(和不同 key2)的行,但我将无法仅使用第一个键访问字典:
var map = new Dictionary<Tuple<string, string>, int>();
map.Add(new Tuple<string, string>(key1, key2), 54);
map.Add(new Tuple<string, string>(key1, key2), 47);
if (map["1"] != null) {} // => this gives an error
有什么想法吗?
【问题讨论】:
-
请记住,
$map{$key1}{$key2} = 54;是( $map{$key1} //= {} )->{$key2} = 54;的缩写,因为它会自动激活。在 C# 中,您需要显式创建子字典。
标签: c# perl dictionary hashmap hashtable