TStringList.CustomSort 的使用原理?
本帖最后由 zhengyc653 于 2012-10-15 17:00:42 编辑 该方法要跟一个 Compare: TStringListSortCompare 类型的函数。
跟进原代码,发现此函数的原型:
function StringListCompareStrings(List: TStringList; Index1, Index2: Integer): Integer;
begin
Result := List.CompareStrings(List.FList[Index1].FString,
List.FList[Index2].FString);
end;
function NumberSort(list: TStringList; index1,
index2: Integer): Integer;
var
value1, value2: Integer;
begin
value1 := StrToInt(list.Strings[index1]);
value2 := StrToInt(list.Strings[index2]); //此处的 Value1 和Value2 取出的是什么值? Index1 和 Index2 又代表什么?
if value1> value2 then //这两个相比较又是什么意思? 返回值又什么意思?
Result := -1
else if value1< value2 then
Result := 1
else
Result := 0;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
strlist: TStringList;
i: Integer;
begin
strlist := TStringList.Create;
try
for i := 1 to 30 do
begin
strlist.Add(IntToStr(random(1000)));
end;
ListBox1.Items.Assign(strlist); //排序前
strlist.CustomSort(NumberSort); //排序后
ListBox2.Items.Assign(strlist);
finally
strlist.Free;
end;
end;