问题描述
我有一种极不可能的情况,就是想从我的属性中返回一个只读数组.到目前为止,我只知道一种实现方法-通过System.Collections.ObjectModel.ReadOnlyCollection<T>
.但这对我来说似乎有些尴尬,更不用说该类失去了按其索引访问数组元素的功能( (added: whoops, I missed the indexer). Is there no better way? Something that could make the array itself immutable?
推荐答案
使用 ReadOnlyCollection<T>
.它是只读的,并且与您所相信的相反,它具有索引器.
Use ReadOnlyCollection<T>
. It is read-only and, contrary to what you believe, it has an indexer.
数组不是一成不变的,没有使用ReadOnlyCollection<T>
这样的包装器就无法使它们成为可能.
Arrays are not immutable and there is no way of making them so without using a wrapper like ReadOnlyCollection<T>
.
请注意,创建ReadOnlyCollection<T>
包装器是O(1)操作,不会产生任何性能成本.
Note that creating a ReadOnlyCollection<T>
wrapper is an O(1) operation, and does not incur any performance cost.
更新
其他答案建议仅将集合转换为较新的 IReadOnlyList<T>
扩展IReadOnlyCollection<T>
以添加索引器.不幸的是,这实际上并不能使您控制集合的可变性,因为它可以转换回原始集合类型并进行突变.
Update
Other answers have suggested just casting collections to the newer IReadOnlyList<T>
, which extends IReadOnlyCollection<T>
to add an indexer. Unfortunately, this doesn't actually give you control over the mutability of the collection since it could be cast back to the original collection type and mutated.
相反,您仍应使用ReadOnlyCollection<T>
(List<T>
方法 AsReadOnly()
或Array
的静态方法 AsReadOnly()
有助于相应地包装列表和数组)以创建对集合的不变访问,然后直接或以其支持的任何接口(包括IReadOnlyList<T>
)公开该访问.
Instead, you should still use the ReadOnlyCollection<T>
(the List<T>
method AsReadOnly()
, or Array
s static method AsReadOnly()
helps to wrap lists and arrays accordingly) to create an immutable access to the collection and then expose that, either directly or as any one of the interfaces it supports, including IReadOnlyList<T>
.
这篇关于在C#中创建只读数组的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!