從下面的結果中,我想知道爲什麼'測試2'的值爲30, 我希望得到與'測試3'(100)相同的結果?爲什麼集合賦值在方法和連續行內的行爲不同?
這裏是提琴手鍊接爲更好的理解。
IList<Test> initialCollection = new List<Test>();
initialCollection.Add(new Test(){ Value = 30});
Console.WriteLine("Test 1 : Before update method : " + initialCollection.Last().Value);
UpdateValueCollection(initialCollection);
Console.WriteLine("Test 2: After update method : " + initialCollection.Last().Value);
IList<Test> check = new List<Test>();
check.Add(new Test(){ Value = 100});
initialCollection = check;
Console.WriteLine("Test 3: Same update method code added as consecutive line : " + initialCollection.Last().Value);
和我的另一種方法是
public void UpdateValueCollection(IList<Test> lstTest)
{
IList<Test> check = new List<Test>();
check.Add(new Test(){ Value = 100});
lstTest = check;
}
的結果是
Test 1 : Before update method : 30
Test 2 : After update method : 30
Test 3 : Same update method code added as consecutive line : 100
因爲C#是通過拷貝通(除非使用'ref'或'out')。當你傳遞引用類型,即參考的副本。您可以改變它所引用的內容,但分配一個新值將不會被調用者看到。 – 2015-04-01 17:25:35