在下面的代碼中,我在基類中有一個屬性,它返回自定義對象的列表。在父類中,我覆蓋了這個屬性,並且在覆蓋的定義中,我從基類訪問對自定義對象列表的引用,並向其中添加2個對象。覆蓋基本屬性並訪問基準中的引用
在返回之前,我在代碼中放置了一個斷點並檢查基本屬性的內容,並注意到兩個新對象不存在。然後,我嘗試將本地對象列表的引用存儲在本地,並再次在列表中添加兩個對象。我注意到在本地引用中添加了2個新對象。
但是,使用這兩種方法我指向相同的引用,所以我應該能夠通過引用base.TestProperty添加對象。任何想法爲什麼這不起作用?
public override List<CustomObject> TestProperty
{
get
{
List<CustomObject> temp = base.TestProperty;
CustomObject obj1 = new CustomObject()
{
Name = "My Name"
};
CustomObject obj2 = new CustomObject()
{
Name = "Your Name"
};
// Adding to the base list
base.TestProperty.Add(obj1);
base.TestProperty.Add(obj2);
// Adding to temp list, which still points to the base list
temp.Add(obj1);
temp.Add(obj2);
// Base object doesnot contain obj1 and obj2, but the temp object does.
return base.TestProperty;
}
}
實施base.TestProperty的PLS – Will
聽起來base.TestProperty返回'新列表()'。 –
您尚未提供足夠的代碼來重現您描述的問題。 – Servy