如何将元素添加到列表<T>类型的属性中?

时间:2020-04-19 17:48:57

标签: c# list

我使用类Form1.csMockProduct.csProduct.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.我的代码有错误吗?


图片1
enter image description here

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

    }

3 个答案:

答案 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)

  1. 如何将元素添加到List类型的属性中?

您使用的是正确的方法:

ProductList.Add (product);
  1. 我的代码有错误吗?

是的,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;
            }
        }