我有一个变量var1
,它是一个包含单个字符串列表的自定义类。我有另一个变量var2
这是一个类似列表var1
。避免在C#中进行深度复制的解决方案
什么,我的目标是什么是我需要遍历var2
,按类类和实例AddRange
串的var1s
名单与var2
的i
个类的自己的字符串列表结合起来。这是独立完成的,这意味着var1
的字符串列表在每次迭代中保持不变。只有在每次迭代时,其字符串列表才会与var2
的字符串列表相结合,但是在迭代之后,它必须恢复为原始字符串。问题是我不能让这个工作。每次我添加一个字符串,它都不会恢复。
我试过做一个深层复制,并在每次迭代结束时将中间克隆类设置为null。有任何想法吗?
下面是一个粗略的 “PeudoCode”
public void combineString(CustomClass var1)
{
// var2 is a class variable that contains a list of CustomClass
List<CustomClass> finalized = new List<CustomClass>();
for (int i = 0; i < var2.Count; i++)
{
CustomClass tmpVar = (CustomClass)var1.Clone();
tmpVar.addString(var2[i].StringSet); //each Custom class has a stringSet which is a list of strings
// .....Do some analysis of the strings of tmpVar
// if it passes the analysis add tmpVar in to finalize list
// none of the other components should change
if (pass analysis)
{
finalized.Add(tmpVar);
}
tmpVar = null;
}
// When the loop is done, the 'finalized' variable is a list of
// CustomClass but then each element inside finalized contains the same string set.
Console.WriteLine("Done");
}
发布您的代码? – 2015-04-04 15:54:29
是的,我正在努力!抱歉! – user1234440 2015-04-04 15:56:47
听起来我可以使用*函数式编程来做到这一点。 – 2015-04-04 16:05:09