我有以下代码:
public void Start()
{
List<StructCustomer> listCustomer = new List<StructCustomer>();
listCustomer.Add(
new StructCustomer { ID = 0, name = "Any Default Name", birthday = DateTime.Now });
DoSomethingWithStructList(listCustomer);
StructCustomer customer = listCustomer.First();
Console.WriteLine("ID = {0}, Name = {1}", customer.ID, customer.name); // Writes ID = 0, Name = "Any Default Name"
}
public void DoSomethingWithStructList(List<StructCustomer> listStructs)
{
StructCustomer test = listStructs.First();
test.ID = 2;
test.name = "Edited by method";
Console.WriteLine("ID = {0}, Name = {1}", test.ID, test.name); // Writes "ID = 2, Name = Edited by method"
}
public struct StructCustomer
{
public int ID { get; set; }
public string name { get; set; }
public DateTime birthday { get; set; }
}
如您所见,变量 List 是对客户列表的引用。不应该在列表的 StructCustomer 变量中编辑值吗?
我知道结构是价值而不是引用类型,但我将它装箱在一个列表中!