如何在C#类构造函数中复制List<string>至对象属性?
解决方法:在构造函数中复制列表到对象属性
你当前的Comenzi构造函数已经接收了_articole参数,但还没有把它赋值给类的Articole属性。另外考虑到引用类型的特性,我们需要选择合适的方式来复制列表,避免后续外部修改影响对象内部数据。
有两种常见的处理方式,你可以根据业务需求选择:
方式1:直接引用赋值(浅拷贝)
这种方式最简洁,但要注意:原列表(ProduseAlese)和对象的Articole属性会指向内存中的同一个列表。如果外部代码修改了ProduseAlese的元素(比如添加、删除操作),Comenzi对象里的Articole也会同步变化。
修改后的构造函数代码:
public Comenzi(int nrcomanda, DateTime datacomanda, DateTime datalivrare, Facturi _factura, List<string> _articole) { NrComanda = nrcomanda; DataComanda = datacomanda; DataLivrare = datalivrare; Factura = _factura; // 直接赋值列表引用 Articole = _articole; }
方式2:创建新列表复制元素(推荐)
这种方式会生成一个全新的列表,把原列表的所有元素复制进去。这样原列表和对象的Articole是完全独立的,外部修改原列表不会影响Comenzi对象内部的数据,这在大多数业务场景下更安全。
修改后的构造函数代码:
public Comenzi(int nrcomanda, DateTime datacomanda, DateTime datalivrare, Facturi _factura, List<string> _articole) { NrComanda = nrcomanda; DataComanda = datacomanda; DataLivrare = datalivrare; Factura = _factura; // 创建新列表并复制所有元素 Articole = new List<string>(_articole); }
如果担心传入的_articole可能为null,可以加个空值判断避免空引用异常:
Articole = _articole != null ? new List<string>(_articole) : new List<string>();
这样即使传入的列表是null,对象的Articole也会被初始化为一个空列表,后续使用时更不容易出错。
内容的提问来源于stack exchange,提问作者Mihail
相关产品推荐
相关产品推荐

