亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

C# 中的 List<struct> VS List<class>

C# 中的 List<struct> VS List<class>

C#
呼如林 2021-10-24 19:43:38
我基于結構創建了一個列表,但無法更改項目值。所以我使用了一個類而不是結構體,但是當我打印列表時出現問題,它給了我根據項目數量插入的最新項目。例如。如果我插入 "A" , "B" , "C" 那么輸出將是 CCC 而不是 ABC這是代碼:public struct Item     //this is working fine but can't change item price{    public string Code { get; set; }    public string Description{ get; set; }    public string Price{ get; set; }    public string Qty { get; set; }}public static Class Item   //this is not working it's overwrite the last value{    public string Code { get; set; }    public string Description{ get; set; }    public string Price{ get; set; }    public string Qty { get; set; }}其余代碼public static Item xItem = new Item();public static List<Item> item = new List<Item>();xItem.Code = txtCode.Text;xItem.Description = txtDescription.text;xItem.Price= txtPrice.text;xItem.Qty = txtQty.text;我嘗試了這兩個(給出相同的結果)item.Insert(i,xItem);// anditem.Add(xItem);在btnSave_Click我添加這個foreach (var s in item){  System.Diagnostics.Debug.WriteLine(s.Code +" \t " + s.Qty);}
查看完整描述

3 回答

?
慕姐8265434

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);


查看完整回答
反對 回復 2021-10-24
?
九州編程

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?


查看完整回答
反對 回復 2021-10-24
  • 3 回答
  • 0 關注
  • 542 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號