我有一些代码可以将数据下载到类中进行存储,然后创建该类的副本以传递给改变数据的方法。不知怎的,我原来的课程也被改变了,我不确定我做错了什么。
Calculations calc = new Calculations(Symbol, Market);
calc.stockData = loadData(Symbol, Market);
for (int j = calc.stockData.Count - 8; j >= 0; j--)
{
highPrice = 0;
// 0 newest
// as you go higher in the index, it is older
for (int k = j + 1; k < j + 8; k++)
{
kIndex = k;
jIndex = j;
decimal highRiskCurrentHigh = Calculations.calculateReturnPercentageStatic(calc.stockData.ElementAtOrDefault(k).Close,
calc.stockData.ElementAtOrDefault(j).High);
if (highRiskCurrentHigh > highPrice)
{
highPrice = highRiskCurrentHigh;
highIndex = k;
}
}
Test test = new Test();
test.returnPct = highPrice;
test.date = calc.stockData.ElementAtOrDefault(highIndex).Date;
test.symbolClass = symbolsList.ElementAtOrDefault(i);
Calculations copy = calc;
test.ratingClass = performCalculations(test.symbolClass, copy, test.date); // passing a copy into the method for altering
stuffList.Add(test); // inserted a breakpoint here and the original class (calc) has been altered
}
答案 0 :(得分:5)
此代码不会创建副本:
Calculations copy = calc;
在C#对象中,所有存在于堆上并通过引用进行操作,与C ++进行比较,您可以在C ++中创建堆栈上的对象,并且赋值等于复制操作。
相反,请实施IClonable
并提供您自己的复制操作。
答案 1 :(得分:3)
答案 2 :(得分:3)
让我们一起浏览您的代码,以便了解这里发生的事情。 (你要告诉你的代码要做的是写在评论中。)
// 1. create a new instance of the object 'Calculations' on the heap
// 2. return the memory address of that instance and assign it to variable 'calc'
Calculations calc = new Calculations(Symbol, Market);
// 3. Create a variable called 'copy' that points to 'Calculations' type objects
// 4. Assign the value of 'calc' (which is a reference to the heap object) to 'copy'
Calculations copy = calc;
简单地说,代码中calc
和copy
指向内存中的同一个对象。这就是copy
的更改正在影响calc
的原因。你需要做的是克隆你的对象,这样你就有了一个值相等但在内存中分开的新对象。