I've got the extremely unlikely and original situation of wanting to return a readonly array from my property. So far I'm only aware of one way of doing it - through the System.Collections.ObjectModel.ReadOnlyCollection<T>
. But that seems somehow awkward to me, not to mention that this class loses the ability to access array elements by their index (added: whoops, I missed the indexer). Is there no better way? Something that could make the array itself immutable?
Use ReadOnlyCollection<T> https://msdn.microsoft.com/en-us/library/ms132474.aspx。它是只读的,并且与您的想法相反,它有一个索引器。
数组不是不可变的,并且没有办法制作它们,因此如果不使用像这样的包装器ReadOnlyCollection<T>
.
请注意,创建一个ReadOnlyCollection<T>
包装器是一个 O(1) 操作,并且不会产生任何性能成本。
Update
其他答案建议将集合投射到较新的版本IReadOnlyList<T> https://msdn.microsoft.com/en-us/library/hh192385.aspx,这延伸了IReadOnlyCollection<T>
添加索引器。不幸的是,这实际上并不能让您控制集合的可变性,因为它可以被强制转换回原始集合类型并发生变化。
相反,您仍然应该使用ReadOnlyCollection<T>
(the List<T>
method AsReadOnly() https://msdn.microsoft.com/en-us/library/e78dcd75.aspx, or Array
静态方法AsReadOnly() https://msdn.microsoft.com/en-us/library/53kysx7b.aspx有助于相应地包装列表和数组)以创建对集合的不可变访问,然后直接公开或作为它支持的任何一个接口公开,包括IReadOnlyList<T>
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)