我有 2 節課
public class Product
{
public DateTime Date { get; set; }
public string Name { get; set; }
public int Amount { get; set; }
}
public class Campaign
{
public long CampaignId { get; set; }
public string CampaignName { get; set; }
public List<Product> Products { get; set; }
}
代碼:
var campaign = new Campaign();
campaign.CampaignId = Item.CampaignId;
campaign.CampaignId = Item.CampaignId;
campaign.CampaignName = Item.CampaignName;
campaign.Products = productList;
campaignList.Add(campaign);
productList.Clear();
當我打電話時productList.Clear(),我的“活動”會洗掉它的campaign.Products.
我怎樣才能防止這種情況發生?
uj5u.com熱心網友回復:
campaign.Products = new List<Product>(productList);
uj5u.com熱心網友回復:
因為campaign.Products 是productList 的相同參考,
它們都指向同一個串列,對一個的任何操作都將反映在另一個變數中
,您需要通過以下不同方式克隆(制作串列的另一個副本)
campaign.Products = productList.GetClone();
或者
campaign.Products = productList.ToList();
或者
campaign.Products.AddRange(productList);
檢查以下網址
https://www.techiedelight.com/clone-list-in-csharp/
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/474277.html
