集合上下文中 ReadOnlyCollection string[] 之间的区别
IList<string> strList = new string[] { "Apple", "Mango", "Orange" };
IList<string> lst = new ReadOnlyCollection<string>(new[]{"Google",
"MSN","Yahoo"});
在这两种情况下,我都无法使用“Add()”方法来添加新项目。然后几乎都 声明是一样的吗?
IList<string> strList = new string[] { "Apple", "Mango", "Orange" };
IList<string> lst = new ReadOnlyCollection<string>(new[]{"Google",
"MSN","Yahoo"});
In both cases i can not use "Add()" method for adding new items.then almost both
declarations are same?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于第一个,
strList[2] = "Pear";
可以工作……但对于第二个则不行。数组始终是可变的,因为您可以通过索引重新分配,即使您无法添加/删除。只读集合就是这样:只读。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.strList
中的项目可以更改(不是添加或删除,而是更改)。The items in
strList
can be changed (not added or removed, but changed).在第一个声明中,您仍然可以使用以下内容:
ReadOnlyCollection
将任何IList
包装在轻量级对象中。它将所有不会更改集合的调用传递给包装对象(getCount
、getItem[]
、GetEnumerator
),但是对所有会更改集合的调用抛出异常(Add
、Remove
、Clear
、setItem[]
)。数组的大小不可调整,但也不是只读的。理解这种区别很重要,否则您可能会引入一些严重的安全问题,例如,请参阅 Path.InvalidPathChars 字段。
In the first declaration, you can still use the following:
ReadOnlyCollection<T>
wraps anyIList<T>
in a lightweight object. It passes all calls that wouldn't change the collection on to the wrapped object (getCount
, getItem[]
,GetEnumerator
), but throws an exception for all calls that would change the collection (Add
,Remove
,Clear
, setItem[]
).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.