我使用类Form1.cs
,MockProduct.cs
和Product.cs
。
要添加新条目,我使用方法:
public partial class Form1: Form
{
public Form1 ()
{
InitializeComponent ();
}
public void AddItem ()
{
Product product = new Product ()
{
ID = 4,
Name = "Name_4",
Description = "Description_4"
};
MockProduct.ProductList.Add (product);
var v = MockProduct.ProductList;
}
}
我正在使用表达式MockProduct.ProductList.Count
检查记录。
结果:MockProduct.ProductList.Count = 3
。
换句话说,该条目未添加。
问题。
1.如何将元素添加到List类型的属性中?
2.我的代码有错误吗?
MockProduct.cs
static class MockProduct
{
static List<Product> productList;
public static List<Product> ProductList
{
get
{
return productList = new List<Product>
{
new Product {ID = 1, Name = "Name_1", Description = "Description_1"},
new Product {ID = 2, Name = "Name_2", Description = "Description_2"},
new Product {ID = 3, Name = "Name_3", Description = "Description_3"},
};
}
set
{
productList = value;
}
}
}
Product.cs
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
答案 0 :(得分:2)
每次调用ProductList
属性的getter时,都会创建并初始化productList
字段的新实例(使用new
运算符),因此总是得到{{ 1}}等于ProductList.Count
。
尝试将此逻辑移到属性外,并在声明3
时仅初始化一次
productList
答案 1 :(得分:1)
如果您想要列表的初始值,则只能在首次访问列表时实例化列表:
get
{
if (productList == null)
{
productList = new List<Product>
{
new Product {ID = 1, Name = "Name_1", Description = "Description_1"},
new Product {ID = 2, Name = "Name_2", Description = "Description_2"},
new Product {ID = 3, Name = "Name_3", Description = "Description_3"},
};
}
return productList;
}
set
{
productList = value;
}
答案 2 :(得分:1)
您使用的是正确的方法:
ProductList.Add (product);
是的,ProductList的获取器总是返回一个新列表。 从MockProduct类中删除以下代码:
public static List<Product> ProductList
{
get
{
return productList = new List<Product>
{
new Product {ID = 1, Name = "Name_1", Description = "Description_1"},
new Product {ID = 2, Name = "Name_2", Description = "Description_2"},
new Product {ID = 3, Name = "Name_3", Description = "Description_3"},
};
}
set
{
productList = value;
}
}