【发布时间】:2018-07-24 13:35:16
【问题描述】:
我根据结构创建了一个列表,但无法更改项目值。所以我使用了一个类而不是结构,但是当我打印列表时出现问题,它根据项目的数量给了我插入的最新项目。
例如。如果我插入 "A" , "B" , "C" 那么输出将是 C C C 而不是 A B C
代码如下:
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);
// and
item.Add(xItem);
在btnSave_Click我添加了这个
foreach (var s in item)
{
System.Diagnostics.Debug.WriteLine(s.Code +" \t " + s.Qty);
}
【问题讨论】:
-
抱歉,现已更新。
-
你应该看看引用类型(=classes)和值类型(=structs)。顾名思义,引用类型是对完全相同实例的引用,而在值类型上,您每次将实例传递给方法时都会复制该实例。
-
你可能不应该使用
struct,除非你已经阅读了它,直到现在坚持使用class。 -
您的基于类的代码中有多少次
new Item()?这就是您创建的Item的实际实例数。您可能对单个实例有多个引用,我怀疑我的问题的答案是 1 - 所以您的列表中存储了 3 个引用,但它们都引用了同一个实例。 -
您只创建一个对象并将其 3 个引用放入同一个列表中。您需要新建 3 个对象。
标签: c# asp.net visual-studio c#-4.0 c#-3.0