Кажется, у меня странная проблема, из-за которой каждый раз, когда я пытаюсь изменить значение элемента в коллекции, это влияет на все остальные, которые содержат те же начальные значения.
Пример ниже:
public class Product : ICloneable
{
public int Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public Product()
{
Id = 0;
Quantity = 0;
}
public Clone()
{
return (Product)this.MemberwiseClone();
}
}
...
private static IEnumerable<Product> GetProducts(Product product, int quantity)
{
for (int i = 0; i < quantity; i++)
{
yield return product.Clone();
}
}
...
IEnumerable<Product> myProducts = Enumerable.Empty<Product>();
Product product1 = new Product() { Id = 0, Name = "Buzz Cola" };
Product product2 = new Product() { Id = 1, Name = "Choco Bites" };
myProducts = myProducts.Concat(GetProducts(product1, 2));
myProducts = myProducts.Concat(GetProducts(product2, 1));
//Now set the quantity of the first product to be 1.
myProducts.ElementAt(0).Quantity = 1;
foreach(Product product in myProducts)
{
Console.WriteLine(string.Format("Id: {0} Quantity: {1}", product.Id, product.Quantity));
}
//Output:
//Id: 0 Quantity: 1
//Id: 0 Quantity: 1 //NO!
//Id: 1 Quantity: 0
Любые идеи?
Большое спасибо!
Обновление Я обновил вопрос, чтобы включить Clone(), как было предложено. Однако выход остается прежним.
myProducts
не имеет свойстваIs
илиQuantity
. Вы имеете в видуproduct.Id
? - person dtb   schedule 24.08.2009