Pregunta

Estoy usando clase genérica TDictionary de Delphi 9. Mis TDictionary es similar al siguiente:

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

Y, por lo que inicializar el TDictionary este modo:

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

Tengo un TList, que yo también estoy inicialización, para que pueda utilizarlo para poblar el TDictionary. Estoy bucle sobre algunos datos del archivo que utilizo para poblar el TList / TDictionary, y estoy tratando de volver a utilizar el mismo TList para insertar en el TDictionary como valor. En la primera inserción en el TDictionary, el valor TList del tema existe y tiene los datos en ella. En la segunda y subsiguientes iteraciones aunque los valores TList son todos nulos.

g_FilePaths := TList<String>.Create;

Me suena como que está haciendo todo esto por referencia. ¿Alguien sabe cómo añadir un TList a mi TDictionary por valor, en lugar de referencia?

Gracias

  // 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;
¿Fue útil?

Solución

El "valor" TList tener es una referencia, por lo que son añadiéndolo por valor. (Adición por referencia significaría que si ha cambiado el valor de g_FilePaths, los valores almacenados en el diccionario cambiarían también, pero eso no sucederá -. Estos valores siguen refiriéndose al mismo objeto TList empezaron con

TDictionary no hace copias en profundidad de los objetos, al igual que ninguna otra cosa. Sólo vamos a tener que morder la bala y crear un nuevo objeto TList para cada elemento que desee agregar. Se puede volver a utilizar el g_FilePaths variable global si se quiere, pero es necesario crear una instancia de un nuevo objeto cada iteración.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top