我有一个自称(递归)的方法。它收集了一些我需要分析的数据。 它收集DTO中的数据。 DTO设置:
public class SequenceDTO
{
public string sequence { get; set; }
public List<Element> stateList { get; set; }
public SequenceDTO()
{ }
public SequenceDTO(string sequence, List<Element> stateList)
{
this.sequence = sequence;
this.stateList = stateList;
}
}
这是我初始化递归方法的方法:
string seq = "";
List<Element> elmList = new List<Element>();
initialSeqDTO.sequence = seq;
initialSeqDTO.stateList = elmList;
analyze(element, initialSeqDTO); //The recursion method
递归方法:
public void handleEventAnalysis3(Element elm, SequenceDTO dto)
{
SequenceDTO newSeqDTO = new SequenceDTO();
List<Element> elmList = new List<Element>();
elmList = dto.stateList;
newSeqDTO.sequence = dto.sequence;
newSeqDTO.stateList = elmList;
newSeqDTO.stateList.Add(clientElement);
if (!clientElement.Name.Equals("Initial"))
handleEventAnalysis3(clientElement, newSeqDTO);
if (clientElement.Name.Equals("Initial"))
{
sequenceList.Add(newSeqDTO);
}
}
这是将SequenceDTO添加到sequenceList。但是每个SequenceDTO的dto.stateList都是相同的。怎么会这样?
答案 0 :(得分:2)
您创建了一个新的List<Element>
:
List<Element> elmList = new List<Element>();
但是你可以通过引用旧列表覆盖它:
elmList = dto.stateList;
相反,您只需致电ToList()
即可生成新列表:
newSeqDTO.stateList = dto.stateList.ToList();
答案 1 :(得分:0)
因为您为每个DTO分配了相同的列表:
elmList = dto.stateList; // this reassigns the variable which makes you lose the newly created list
newSeqDTO.sequence = dto.sequence;
newSeqDTO.stateList = elmList
如果你只删除这一行就可以了:
elmList = dto.stateList;