2010-08-12 79 views
0

我怎样才能找到名称并获得对象集合中的Item?delphi 7:我怎样才能找到对象集合的项目?

procedure TfoMain.InitForm; 
    begin 
     // Liste des produits de la pharmacie 1 
     FListeDispoProduit := TListeDispoProduit.Create(TProduit); 

     with (FListeDispoProduit) do 
     begin 
     with TProduit(Add) do 
     begin 
      Name := 'Produit 01'; 
      CIP := 'A001'; 
      StockQty := 3; 
      AutoRestock := 1; 
      QtyMin:= 2; 
     end; 

     with TProduit(Add) do 
     begin 
      Name := 'Produit 02'; 
      CIP := 'A002'; 
      StockQty := 5; 
      AutoRestock := 0; 
      QtyMin:= 2; 
     end; 



function getProductByName(productName: String): TProduit; 
    var 
     i : integer; 
    begin 
     for i := 0 to fProductList.Count -1 do 
     begin 
     if (TProduit(fProductList.Items[i]).Name = productName) 
      Result := 
     end; 
    end; 

我想编辑有关产品名称的数量。

我该怎么做? 谢谢

+0

哪个Delphi版本? – 2010-08-12 14:42:05

+0

您在编写我的答案时编辑了您的问题,现在看起来您已经知道如何识别列表中的项目。既然你已经知道答案,你真的在​​问什么? – 2010-08-12 14:58:50

回答

1

如果您的收集对象是TCollection,那么它具有Items属性(您应该已经在文档或源代码中看到该属性)。使用它和它的Count属性编写一个循环,您可以在其中检查每个项目以查看它是否与您的目标匹配。

var 
    i: Integer; 
begin 
    for i := 0 to Pred(FListeDespoProduit.Count) do begin 
    if TProduit(FListeDespoProduit.Items[i]).Name = productName then begin 
     Result := TProduit(FListeDespoProduit.Items[i]); 
     exit; 
    end; 
    end; 
    raise EItemNotFound.Create; 
end; 

Itemsdefault property,这意味着你可以从你的代码忽略它,只是本身使用数组索引。您可以将它缩短为FListeDespoProduit[i]而不是FListeDespoProduit.Items[i]

0

您的TProduit工具(Add)。它尚未实现(Get)(或类似的东西)?

你是继承这个代码吗?是否有更多细节?

编辑:否则你必须自己创建Get过程,可能是通过遍历列表并找到匹配,然后返回它。

+0

我编辑我的代码,但如何返回产品对象? – TimeIsNear 2010-08-12 14:52:18

+1

以您处理它的相同方式进行。将其分配给Result变量,然后“退出”或“中断”。不同的是,“退出”退出程序,而“休息”只退出“for i:= 0 to fProductList.Count-1”循环。 – himself 2010-08-12 15:09:27

0
function getProductByName(productName: String): TProduit; 
    var 
    i : integer; 
begin 
    for i := 0 to fProductList.Count -1 do 
    begin 
    if (TProduit(fProductList.Items[i]).Name = productName) 
     Result := TProduit(fProductList.Items[i]); // this??? 
    end; 
end; 

然后,您可以去:

MyProduit := getProductByName('banana'); 
MyProduit.StockQty := 3; 

或任何你想。