清单< T> .AsReadOnly()VS IReadOnlyCollection< T> [英] List<T>.AsReadOnly() vs IReadOnlyCollection<T>

查看:110
本文介绍了清单< T> .AsReadOnly()VS IReadOnlyCollection< T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

列表< T> 工具 IReadOnlyCollection< T> 接口,并提供了 AsReadOnly( )方法,它返回 ReadOnlyCollection还< T> (这反过来工具 IReadOnlyCollection< T> )。

List<T> implements IReadOnlyCollection<T> interface and provides the AsReadOnly() method which returns ReadOnlyCollection<T> (which in turn implements IReadOnlyCollection<T>).

有什么用途/原因 AsReadyOnly()? T>的一个或两个边缘情况下,刚刚返回列表, IReadOnlyCollection<它的存在气味是滥竽充数不好。

What is the usage/reason for AsReadyOnly()? Its existence smells of one or two edge cases where just returning the list as IReadOnlyCollection<T> is just not good enough.

起初我以为这可能是防止铸件成本内斯遥远,但它看起来像你可以做到这一点与 ReadOnlyCollection还< T> 产品访问。

At first I though it may be to prevent casting the cost-ness away but it looks like you can do that with ReadOnlyCollection<T>'s Items accessor.

BTW。有关文档 ReadOnlyCollection还< T> 类型读

BTW. The documentation for ReadOnlyCollection<T> type reads

提供的基类的一般只读集合。

Provides the base class for a generic read-only collection.

这在我的头上,具有描述为

which, in my head, conflicts with having a constructor described as

初始化(...)类是围绕指定列表的只读包装的新实例

Initializes a new instance of the (...) class that is a read-only wrapper around the specified list.

更新:
我没有看到 ReadOnlyCollection还< T>的 项目是受保护的。

推荐答案

如果你只返回一个实际的列表< T> 作为 IReadOnlyList< T> ,那么调用者总是可以只投回来,然后修改名单变就变。相反,调用 AsReadOnly()创建名单,其中消费者无法更新只读包装。

If you just return an actual List<T> as an IReadOnlyList<T>, then the caller can always just cast it back, and then modify the list as they please. Conversely, calling AsReadOnly() creates a read-only wrapper of the list, which consumers can't update.

注意只读包装将反映基础列表所做的更改,所以可以访问原始列表代码仍然可以与知识的只读版本的消费者将看到这些变化进行更新。

Note that the read-only wrapper will reflect changes made to the underlying list, so code with access to the original list can still update it with the knowledge that any consumers of the read-only version will see those changes.

这篇关于清单&LT; T&GT; .AsReadOnly()VS IReadOnlyCollection&LT; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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