在上一个(从列表中删除空字符串)问题我询问有关从字符串列表中删除空字符串
....
// Clear out the items that are empty
for I := mylist.count - 1 downto 0 do
begin
if Trim(mylist[I]) = '' then
mylist.Delete(I);
end;
....
Run Code Online (Sandbox Code Playgroud)
从代码设计和重用的角度来看,我现在更喜欢一个更灵活的解决方案:
MyExtendedStringlist = Class(TStringlist)
procedure RemoveEmptyStrings;
end;
Run Code Online (Sandbox Code Playgroud)
问:在这种情况下我可以使用类助手吗?与上面设计一个新课程相比,这会是什么样子?
这里有一个好帮手.为了使其更广泛适用,您应该选择将帮助程序与帮助程序可以应用的派生类最少的类相关联.在这种情况下,这意味着TStrings.
派生新类的巨大优势在于,您的辅助方法可用于TStrings不是由您创建的实例.明显的例子包括TStrings公开备忘录,列表框等内容的属性.
我个人会编写一个帮助程序,使用谓词提供更一般的删除功能.例如:
type
TStringsHelper = class helper for TStrings
public
procedure RemoveIf(const Predicate: TPredicate<string>);
procedure RemoveEmptyStrings;
end;
procedure TStringsHelper.RemoveIf(const Predicate: TPredicate<string>);
var
Index: Integer;
begin
for Index := Count-1 downto 0 do
if Predicate(Self[Index]) then
Delete(Index);
end;
procedure TStringsHelper.RemoveEmptyStrings;
begin
RemoveIf(
function(Item: string): Boolean
begin
Result := Item.IsEmpty;
end;
);
end;
Run Code Online (Sandbox Code Playgroud)
更一般地说,TStrings是班主任的优秀候选人.它缺少相当多的有用功能.我的助手包括:
AddFmt格式化和添加的方法.AddStrings在一次调用中添加多个项目的方法.Contains方法,它包装IndexOf(...)<>-1并为未来的代码读者提供一种语义更有意义的方法.Data[]属性,类型NativeInt,和匹配AddData方法,封装了Objects[]属性.这隐藏了TObject和之间的演员阵容NativeInt.我确信可以添加更多有用的功能.
您可以使用HelperClass,但您应该基于TStrings,这将提供更大的灵活性.
一个例子可能是:
type
TMyStringsClassHelper = class helper for TStrings
Procedure RemoveEmptyItems;
end;
{ TMyStringsClassHelper }
procedure TMyStringsClassHelper.RemoveEmptyItems;
var
i:Integer;
begin
for i := Count - 1 downto 0 do
if Self[i]='' then Delete(i);
end;
procedure TForm5.Button1Click(Sender: TObject);
var
sl:TStringList;
begin
sl:=TStringList.Create;
sl.Add('AAA');
sl.Add('');
sl.Add('BBB');
sl.RemoveEmptyItems;
Showmessage(sl.Text);
Listbox1.Items.RemoveEmptyItems;
Memo1.Lines.RemoveEmptyItems;
sl.Free;
end;
Run Code Online (Sandbox Code Playgroud)