开发者

Am I imagining things? List being made a reference to a second list instead of being made a copy of the second list

This code seems to be making _cleanRepos开发者_如何学GoitoryCollection a reference to _currentTextFile.RepositoryCollection instead of making it a copy of _currentTextFile.RepositoryCollection:

_cleanRepositoryCollection = _currentTextFile.RepositoryCollection;

The datatype is List<Repository>.


No, you're not imagining things. That stores a reference to the list returned by _currentTextFile.RepositoryCollection.

Now, this may be a reference to _currentTextFile's internal RepositoryCollection list, or it may be a copy -- it depends on the implementation of the RepositoryCollection property.

If you want to ensure that you have a copy, you need to make the copy yourself.


Working as intended.

Try _cleanRepositoryCollection = new List<Repository>(_currentTextFile.RepositoryCollection);


Yep, that's the first thing any .NET developer should learn - the differences between reference types and value types and the reference vs copy behaviors they exhibit.

Having said that, if the collection is not intended to be modified by code outside of the class, the internal list should not be exposed directly through a property. You can make a true clone of the list just by doing:

private List<Foo> internalList;

public List<Foo> RepositoryCollection {
    get {
        return new List<Foo>(interalList);
    }
}

Or if you just want to return a read-only wrapper to the caller so that they cannot modify your internal structure, you can do:

private List<Foo> internalList;
private ReadOnlyCollection<Foo> externalList;

public ReadOnlyCollection<Foo> RepositoryCollection {
    get {
        if (externalList == null) {
            externalList = internalList.AsReadOnly();
        }
        return externalList;
    }
}

In the second example, the returned collection is a read-only wrapper but it is not a snapshot at the time AsReadOnly was called. If you added an item to internalList, it would be reflected in externalList.


List is a reference type. Hence in assigning it to _cleanRepositoryCollection you are assigning a reference to the same instance not copying the list (which in most scenarios would be inefficient).

I would suggest that the class you use for _currentTextFile should expose a CleanRepositoryCollection property that internally copies the collection (try new List(_currentTextFile.RepositoryCollection); as suggested in one of the other answers) and exposes IEnumerable. That ensures that the clients are not using an interface that can modify the collection and that they can't get around it by casting. Modifying the collection should be performed using appropriate business methods on _currentTextFile.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜