2010-08-12 78 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; 

或任何你想。