代码之家  ›  专栏  ›  技术社区  ›  Ryan

Delphi的TDictionary,my Value对象作为null插入

  •  1
  • Ryan  · 技术社区  · 15 年前

    g_FileHandlers : TDictionary<String, TList<String>>;
    

    所以我初始化TDictionary如下:

    g_FileHandlers := TDictionary<String, TList<String>>.Create;
    

    我有一个TList,我也在初始化它,这样我就可以用它来填充TDictionary。我循环使用一些用于填充TList/TDictionary的文件数据,并尝试重新使用相同的TList作为值插入TDictionary。在第一次插入到TDictionary时,该项的TList值存在并包含数据。在第二次迭代和随后的迭代中,尽管TList值都是nil。

    g_FilePaths := TList<String>.Create;
    

    在我看来,这一切都是通过参考来实现的。如何通过值而不是引用将TList添加到我的TDictionary?

      // Create our dictionary of files and handlers
      for i := 0 to g_FileList.Count - 1 do
      begin
        g_HandlerName := AnsiMidStr(g_FileList[i], 2, Length(g_FileList[i]));
        g_HandlerName := AnsiMidStr(g_HandlerName, 1, Pos('"', g_HandlerName) - 1);
    
        if i = 0 then
          g_PreviousHandlerName := g_HandlerName;
    
        if AnsiCompareText(g_HandlerName, g_PreviousHandlerName) = 0 then
        begin
          g_FilePath := AnsiMidStr(g_FileList[i], Length(g_HandlerName) + 5, Length(g_FileList[i]));
          g_FilePath := AnsiMidStr(g_FilePath, 1, Length(g_FilePath) - 1);
          g_FilePaths.Add(g_FilePath);
        end
        else
        begin
          g_FileHandlers.Add(g_PreviousHandlerName, g_FilePaths);
    
          g_FilePaths.Clear;
          g_FilePath := AnsiMidStr(g_FileList[i], Length(g_HandlerName) + 5, Length(g_FileList[i]));
          g_FilePath := AnsiMidStr(g_FilePath, 1, Length(g_FilePath) - 1);
          g_FilePaths.Add(g_FilePath);
        end;
    
        if AnsiCompareText(g_HandlerName, g_PreviousHandlerName) <> 0 then
          g_PreviousHandlerName := g_HandlerName;
    
        if i = g_FileList.Count - 1 then
          g_FileHandlers.Add(g_HandlerName, g_FilePaths);
      end;
      g_FilePaths.Free;
    
    1 回复  |  直到 5 年前
        1
  •  2
  •   Rob Kennedy    15 年前

    推荐人,所以你 g_FilePaths ,则字典中存储的值也会更改,但这不会发生这些值继续引用它们开始使用的同一TList对象。

    TDictionary不会像其他任何东西一样对对象进行深度复制。您只需咬紧牙关,为每个要添加的项创建一个新的TList对象。可以重用全局变量 如果需要,但每次迭代都需要实例化一个新对象。