IList<string> strList = new string[] { "Apple", "Mango", "Orange" };
IList<string> lst = new ReadOnlyCollection<string>(new[]{"Google",
"MSN","Yaho开发者_C百科o"});
In both cases i can not use "Add()" method for adding new items.then almost both declarations are same?
With the first, strList[2] = "Pear";
will work... not with the second. Arrays are always mutable in that you can re-assign by index, even if you can't add/remove. A read-only-collection is just that: read-only.
The items in strList
can be changed (not added or removed, but changed).
In the first declaration, you can still use the following:
strList[0] = "Not a fruit";
ReadOnlyCollection<T>
wraps any IList<T>
in a lightweight object. It passes all calls that wouldn't change the collection on to the wrapped object (get Count
, get Item[]
, GetEnumerator
), but throws an exception for all calls that would change the collection (Add
, Remove
, Clear
, set Item[]
).
Arrays are not resizable, but they are not readonly. The distinction is important to understand or you can introduce some serious security issues, for an example see Path.InvalidPathChars Field.
精彩评论