读书人

TStringList.CustomSort 的施用原理

发布时间: 2012-11-12 12:31:58 作者: rapoo

TStringList.CustomSort 的使用原理?
该方法要跟一个 Compare: TStringListSortCompare 类型的函数。
跟进原代码,发现此函数的原型:

Delphi(Pascal) code
function StringListCompareStrings(List: TStringList; Index1, Index2: Integer): Integer;begin  Result := List.CompareStrings(List.FList[Index1].FString,                                List.FList[Index2].FString);end;

看了Delphi的原码,Index1 和 Index2 好像是StringList的 Low 和 High,但怎么利用这两个参数呢?
看到网上的一段代码:
Delphi(Pascal) code
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;

完全看不明白,有哪位高手可以帮我逐行解释一下吗?


[解决办法]
listview采取快速排序,快速排序需要比较两项数据大小,但你无法比较两个listitem的大小,对吧?所以你需要一个自定义函数:function NumberSort(list: TStringList; index1, index2: Integer): Integer;
其中 index1, index2表示待比较两个项序号,程序员可根据自己需要完善比较函数,用以排序

读书人网 >.NET

热点推荐