swaping a collection with defensive copy
T开发者_运维百科his is an example I have seen in the Effective C# book:
private BindingList<PayrollData> data;
public IBindingList MyCollection
{
get { return data; }
}
public void UpdateData()
{
// Unreliable operation might fail:
var temp = UnreliableOperation();
// This operation will only happen if
// UnreliableOperation does not throw an
// exception.
data = temp;
}
The author says this will work for value type and not for reference type. I couldn't understand what he meant.
I think I now understand: a collection is a ref type. consumers of "data field" won't remeber they a re holding a copy to the old storage on the heap. if "data" was value type - the consumers (other code that uses data) will remeber they are holding a deep copy of data and will ask for it again when need to update.
right ?
The collection is a reference type, so other holding code onto that will see the old data.
Two possible solutions:
Instead of data = temp use data.Clear(); data.AddRange(temp) which will change the contents of the data field.
Or better delete the MyCollection property and make class implement IEnumerable. This results in much better encapsulation.
精彩评论