开发者

C#, SynchronizedReadOnlyCollection and its constructors

.net class SynchronizedReadOnlyCollection has 4 constructors.

    public SynchronizedReadOnlyCollection();
    public SynchronizedReadOnlyCollection(object syncRoot);
    public SynchronizedReadOnlyCollection(object syncRoot, IEnumerable<T> list);
    public SynchronizedReadOnlyCollection(object syncRoot, params T[] list);

What is the use of the parameterless constructor and the constructor with only the lock object? The collection will always be empty if you don't fill the collection when you create the collection? Do I 开发者_高级运维miss something?


At some point it is possible that you need an empty collection, e.g. if you are initializing a class and data isn't known when the constructor is called. If you don't assign an empty collection, other code might fail if it tries to access that field/property and throws a NullReferenceException. If data is supplied at a later stage, that code simply replaces the field with a new, filled instance of SynchronizedReaOnlyCollection.


public SynchronizedReadOnlyCollection();

Initializes a new empty collection which will lock on an internal field.

public SynchronizedReadOnlyCollection(object syncRoot);

Initializes a new empty collection which will lock on an object you provide.

public SynchronizedReadOnlyCollection(object syncRoot, IEnumerable<T> list);

Initializes a new collection containing the elements in the list which will lock on an object you provide.

The documentation does a good job explaining this. It's worth reading.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜