代码之家  ›  专栏  ›  技术社区  ›  Marco van de Voort

t词典。在交互时设置valuetype值

  •  0
  • Marco van de Voort  · 技术社区  · 7 年前

    第一次天真的尝试:

    var p: tpair<keytype,valuetype>;
    
    begin
      for p in coll do
        // p.value is readonly for valuetypes and their fields.
     end;
    

    失败,并且在记录中包装valuetype也没有帮助。

    在键上迭代并使用dosetvalue可能有效,但它仅是私有的。

    添加,完整样本:

    program gendicttest;
    //  tests if you can set valuetype key.
    
    {$APPTYPE CONSOLE}
    
    uses
      generics.collections;
    
    type
      TCycleList = tdictionary<integer,integer>; // the value a record type doesn't work either.
    
    var cyclelist :TCycleList;
        p : tpair<integer,integer>;
        j:integer;
    begin
      cyclelist:=tcyclelist.Create;
      cyclelist.Add(3,4);
      for  p in cyclelist do
        writeln(p.Key, ' ',p.Value);
    
      if cyclelist.TryGetValue(3,j) then
        cyclelist.AddOrSetValue(3,j+1);
      for  p in cyclelist do
       p.Value:=0;     // <-- here, and alternative to do this.r
    
      for  p in cyclelist do
        writeln(p.Key, ' ',p.Value);    
    end.
    
    0 回复  |  直到 7 年前
        1
  •  1
  •   Rudy Velthuis    7 年前

    当然不行了!返回的一对是副本。所以你充其量只能修改副本,这毫无意义。

    如果只想清除值,则获取键的副本并对其进行枚举,以将每个键的值设置为0。

    for var I in cycleList.Keys do
      cycleList.AddOrSetValue(I, 0);
    

    for var I in cycleList.Keys do
      cycleList.Items[I] := 0;
    

    注意:也可以不使用Rio语法