当值设置为空时,是否可以阻止TStringlist删除键值对

时间:2015-11-24 12:09:37

标签: delphi

当value设置为empty时,我可以阻止TStringList删除键值对吗?我使用的Delphi XE8和Lazarus的工作方式不同。我希望将该对保留在TStringlist对象中,即使该值设置为空字符串也是如此。例如:

procedure TMyClass.Set(const Key, Value: String);
begin
  // FData is a TStringList object
  FData.Values[Key] := Value; // Removes pair when value is empty. Count decreases and Key is lost.
end;

我遇到的问题是,当我使用Delphi编译时,删除了具有空值的对,之后我不知道是一个未设置密钥的值,或者它是否明确设置为空字符串。此外,我无法获得所有已使用的密钥。现在我需要保存另一个包含空信息的密钥集合。

MyKeyValues.Set('foo', 'bar'); // Delphi FData.Count = 1; Lazarus FData.Count = 1
MyKeyValues.Set('foo', '');    // Delphi FData.Count = 0; Lazarus FData.Count = 1

3 个答案:

答案 0 :(得分:3)

您可以编写class helper来实现SetValue类的TStrings方法的新行为。

如果您不喜欢基于类帮助程序的解决方案,则可以使用继承自TStringList的自定义类,并再次覆盖其Values属性行为 - 代码为与基于帮助程序的实现非常相似。

我更喜欢使用第二种选择,因为帮助程序将为所有TStringList对象定义新行为。

type
  TStringsHelper = class helper for TStrings
    private
      function GetValue(const Name: string): string;
      procedure SetValue(const Name, Value: string); reintroduce;
    public
      property Values[const Name: string]: string read GetValue write SetValue;
  end;


function TStringsHelper.GetValue(const Name: string): string;
begin
  Result := Self.GetValue(Name);
end;

procedure TStringsHelper.SetValue(const Name, Value: string);
var
  I: Integer;
begin
  I := IndexOfName(Name);
  if I < 0 then I := Add('');
  Put(I, Name + NameValueSeparator + Value);
end;

答案 1 :(得分:1)

这个怎么样?

procedure TMyClass.Set(const Key, Value: String);
var
  i:integer;
begin
  i := FData.IndexOfName(Key);
  if i = -1 then
    FData.Add(Key + '=' + Value)
  else
    FData[i] := Key + '=' + Value;
end;

您可以选择是否设置FData.Sorted:=true;

答案 2 :(得分:0)

TStringList没有选项。当值为空('')时,其行为是删除条目。

您可以自己实现该行为,例如,在您的值中添加类似前缀的内容:

procedure TMyClass.Set(const Key, Value: String);
begin
  FData.Values[Key] := '_' + Value;
end;

但这意味着,您还需要一个吸气剂,再次将其删除:

function TMyClass.Get(const Key): String;
begin
  Result := StringReplace(FData.Values[Key], '_', '', []);
end;