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

All*_*ala 6 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;
Run Code Online (Sandbox Code Playgroud)

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

MyKeyValues.Set('foo', 'bar'); // Delphi FData.Count = 1; Lazarus FData.Count = 1
MyKeyValues.Set('foo', '');    // Delphi FData.Count = 0; Lazarus FData.Count = 1
Run Code Online (Sandbox Code Playgroud)

fan*_*cco 4

您可以编写一个类助手来实现新的行为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;
Run Code Online (Sandbox Code Playgroud)