如何向列表中添加元素而不出现VyRef问题

huangapple go评论77阅读模式
英文:

how to add elements to a list without the VyRef problem

问题

我希望列表的每次迭代都能存储新的值。
英文:

I am creating a list of objects but every time I add a new element to the list, it modifies the previous elements.

private List<DocRequisicionTransferModel> sendReqMultiple(DocRequisicionTransferModel docRequisicionTransferModel)
        {
            List<DocRequisicionTransferModel> data = new  List<DocRequisicionTransferModel>();
            //doctoReqTransfer.MovimientoRequisicionTransferencia = docRequisicionTransferModel.MovimientoRequisicionTransferencia;
            List<MovRequisicionTransferModel> movRequisicionTransferModels = new List<MovRequisicionTransferModel>();
            movRequisicionTransferModels = docRequisicionTransferModel.MovimientoRequisicionTransferencia;
            List<String> distinctBodegas = docRequisicionTransferModel.MovimientoRequisicionTransferencia.Select(movto => movto.IdBodegaSal).Distinct().ToList();
    

            foreach (String bodega in distinctBodegas)
            {
                if (!String.IsNullOrEmpty(bodega))
                {
                    DocRequisicionTransferModel doctoReqTransfer = new DocRequisicionTransferModel();
                    doctoReqTransfer = docRequisicionTransferModel;
                    doctoReqTransfer.IdBodegaSal = bodega;
                    doctoReqTransfer.MovimientoRequisicionTransferencia = movRequisicionTransferModels.Where(movto => movto.IdBodegaSal.Equals(bodega)).ToList();
                    data.Add(doctoReqTransfer);

                }
                
            } 

            return data;

I expect each iteration of the list to store new values

答案1

得分: 0

你的代码中没有隐藏的问题。只是你犯了逻辑错误:

DocRequisicionTransferModel doctoReqTransfer = new DocRequisicionTransferModel(); // 创建了一个新对象,但doctoReqTransfer的值会在后续被覆盖
doctoReqTransfer = docRequisicionTransferModel; // 在每次迭代中,你在这里分配了相同的值

如果你需要创建新的doctoReqTransfer,并将其从docRequisicionTransferModel复制过来,可以在DocRequisicionTransferModel类中添加复制构造函数。

英文:

There is no hidden problem behind your code. Just you made the logical error:

DocRequisicionTransferModel doctoReqTransfer = new DocRequisicionTransferModel(); // new object is created, but the value of doctoReqTransfer overwrites further  
doctoReqTransfer = docRequisicionTransferModel; // here you assign the same value in each iteration

If you need to create the new doctoReqTransfer copying it from docRequisicionTransferModel, add the copying constructor to the DocRequisicionTransferModel class.

huangapple
  • 本文由 发表于 2023年7月28日 05:21:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76783473.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定