在 C# 中创建只读数组的最佳方法是什么? [英] What's the best way of creating a readonly array in C#?

查看:54
本文介绍了在 C# 中创建只读数组的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的财产中返回一个只读数组是极不可能和原始的情况.到目前为止,我只知道一种方法 - 通过 System.Collections.ObjectModel.ReadOnlyCollection.但这对我来说似乎有些尴尬,更不用说这个类失去了通过索引访问数组元素的能力(补充说:哎呀,我错过了索引器).没有更好的办法吗?可以使数组本身不可变的东西?

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?

推荐答案

使用 <代码>ReadOnlyCollection.它是只读的,并且与您所相信的相反,它有一个索引器.

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 包装器是一个 O(1) 操作,不会产生任何性能成本.

Note that creating a ReadOnlyCollection<T> wrapper is an O(1) operation, and does not incur any performance cost.

更新
其他答案建议只将集合转换为较新的 IReadOnlyList<T>,它扩展了 IReadOnlyCollection 以添加索引器.不幸的是,这实际上并不能让您控制集合的可变性,因为它可能会被转换回原始集合类型并发生变异.

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(List 方法 AsReadOnly()Array 的静态方法 AsReadOnly() 有助于相应地包装列表和数组)以创建不可变的访问该集合,然后直接或作为它支持的任何一种接口公开该集合,包括 IReadOnlyList.

Instead, you should still use the ReadOnlyCollection<T> (the List<T> method AsReadOnly(), or Arrays 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# 中创建只读数组的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆