3 回答

TA貢獻1813條經驗 獲得超2個贊
聽起來您正在重復使用該xItem對象。您需要為列表中的每個項目創建一個新項目。該列表只是一個對象引用列表,目前它們都指向同一個實際對象。例如這個代碼:
public static Item xItem = new Item();
public static List<Item> list = new List<Item>();
xItem.Code = "A";
xItem.Description = "A";
xItem.Price= "1";
xItem.Qty = "1";
list.Add(xItem);
//list now has 'A' with value of 1 in it..
xItem.Code = "B"
//without any further change, list will now have the same
//item, so its Code will now be "B":
//this will be TRUE:
var listIsNowB = (list[0].Code == "B");
相反,您需要這樣做:
xItem.Code = "A";
xItem.Description = "A";
xItem.Price= "1";
xItem.Qty = "1";
list.Add(xItem);
//we're now done with that *instance* of Item, so we now create a *new* one.
//we can re-use our variable without problem though.
xItem = new Item();
xItem.Code = "B";
xItem.Description = "B";
xItem.Price= "2";
xItem.Qty = "2";
//xItem is a new object, so this will work as you expect now.
list.Add(xItem);

TA貢獻1785條經驗 獲得超4個贊
這是由于引用和值類型語義。甲參考型(=類)僅僅是一個指針,指向一個實例。因此,當您將一個對象傳遞給方法時,您實際上提供了一個指向該對象的指針,而不是實際的對象。您通過該引用更改的所有內容都會反映在對該實例的所有引用上。
在您的情況下,您只有一個用于不同實例語義的引用。因此創建一個新實例而不是重新使用現有實例:
public static Item xItem = new Item();
public static List<Item> item = new List<Item>();
...
xItem = new Item();
xItem.Code = txtCode.Text;
xItem.Description = txtDescription.text;
xItem.Price= txtPrice.text;
xItem.Qty = txtQty.text;
順便說一句,結構通常應該是不可變的。因此,無論何時您打算修改實例狀態,您都應該考慮使用類而不是結構。要進一步了解 immutablilty,您還可以閱讀這篇文章:Why are C# structs immutable?
- 3 回答
- 0 關注
- 542 瀏覽
添加回答
舉報