我有一個程序,其中我有三個類A,B和C. A含有構件是B的列表,並且B由這是一個成員的問題C的列表。 A包含一個名爲RemoveB()的方法,同樣B包含一個名爲RemoveC()的方法。 RemoveB()和RemoveC()分別刪除BList和CList的第一個元素。在列表的列表中刪除的元素在C#
下面就是這一切的樣子:
class A
{
...
List<B> BList;
...
public void RemoveB()
{
this.BList.Removeat(0)
}
}
class B
{
...
List<C> CList;
...
public void RemoveC()
{
this.CList.Removeat(0)
}
}
class Trial
{
...
}
在我的主要功能我第一次填充BList和分欄列表中的每個BList元素。 BList中有N個元素,每個BList元素都包含CList中的M個元素。然後我做了以下。
A aObject = new A(); // Populates BList and CList.
for(int i = 0; i < N; i++)
{
Console.WriteLine("BList: {0} ({1})", i, aObject.BList[0].Count);
for (int j = 0; j < M; j++)
{
Console.WriteLine("CList: {0}", j);
aObject.BList[0].RemoveC();
}
aObject.RemoveB();
}
當我這樣做時,出現以下問題。當我嘗試除去屬於元件BList在分欄列表元素[0],在分欄列表相應的元件在BList [1],BList [2] ... BList [N-1]也被除去。 以下是我從運行程序中看到的輸出。
BList 0 (M)
CList 0
CList 1
CList 2
.
.
.
CList M-1
BList 1 (0)
BList 2 (0)
BList 3 (0)
.
.
.
BList N-1 (0)
有人能告訴我爲什麼會發生這種情況嗎?我在某處做了一些根本性的錯誤嗎?
謝謝你們!我解決了這個問題。這是一個參考問題。我用同一個對象複製到列表中,這是所有問題的根源。 – siva82kb