2010-06-06 102 views
0

复制放置在项目列表中的对象并更改重复对象的属性的最佳方法是什么?如何复制列表中的对象并更新重复对象的属性?

我想继续通过以下方式: - 根据需要(n次)克隆找到对象多次 - - 由“裁判” +“文章” 获取列表对象中删除对象中找到 - 添加列表中的克隆

您认为如何?

一个具体的例子:

Private List<Product> listProduct; 
listProduct= new List<Product>(); 

Product objProduit_1 = new Produit; 

objProduct_1.ref = "001"; 
objProduct_1.article = "G900"; 
objProduct_1.quantity = 30; 

listProducts.Add(objProduct_1); 

ProductobjProduit_2 = new Product; 

objProduct_2.ref = "002"; 
objProduct_2.article = "G900"; 
objProduct_2.quantity = 35; 

listProduits.Add(objProduct_2); 

期望的方法:

public void updateProductsList(List<Product> paramListProducts,Produit objProductToUpdate, int32 nbrDuplication, int32 newQuantity){  
...  
} 

调用方法例如:

updateProductsList(listProducts,objProduct_1,2,15); 

等待结果:

替换跟随对象:

ref = "001"; 
article = "G900"; 
quantite = 30; 

通过:

ref = "001"; 
article = "G900"; 
quantite = 15; 

ref = "001"; 
article = "G900"; 
quantite = 15; 

的算法是正确的?你有一个想法的方法实施“updateProductsList”

谢谢您的帮助。

+0

这是C#,对不起!我已经删除了java标志。 – TimeIsNear 2010-06-06 14:08:33

回答

0

首先,它看起来像你想实现自己的ProductList对象。当延伸List<Product>时,实施很简单。其次,要更新产品,您可以删除旧产品,将其克隆两次并添加两次。

public class ProductList : List<Product> { 
    public void update(Product product, int nrOfDuplications, int newQuantity) { 
     Remove(product); 
     for(int i = 0; i < nrOfDuplications; i++) { 
      Add(new Product() { 
       ref = product.ref, 
       article = product.article, 
       quantity = newQuantity 
      }); 
     } 
    } 
} 

这可以通过使用一个copy constructor,这意味着你并不需要所有的部件的完整列表,有待进一步提高。

+0

感谢您的回复,我确实发现了您的解决方案。出于好奇,有没有符合我需求的模式? 比只有一个属性更改的重复对象更好。 谢谢 – TimeIsNear 2010-06-11 21:56:32

相关问题