问题描述
在C#中获取一个类型为只读的空列表的标准方法是什么?
ETA: 为什么?:我有一个虚方法返回一个 IList
(或者更确切地说,后回答,一个 IEnumerable
),并且默认实现为空。无论列表返回应该是readonly,因为写入它将是一个错误,如果有人尝试,我想停止并立即着火,而不是等待错误以后稍微显露出来。
我个人认为这比任何其他答案更好:
static readonly IList< T> EmptyList = new T [0];
- 数组实现
IList< T& code>。
- 不能添加到数组。
- 不能将元素分配到空数组( none none)。
- 这是我认为比
new List< T& code>。
- 您仍然可以返回
IList< T>
(如果需要)。
顺便说一句,这是 Enumerable.Empty< T>()
所以理论上你甚至可以做(IList< T>)Enumerable.Empty< T>()
(虽然我没有很好的理由这样做)。
What's the standard way to get a typed, readonly empty list in C#, or is there one?
ETA: For those asking "why?": I have a virtual method that returns an IList
(or rather, post-answers, an IEnumerable
), and the default implementation is empty. Whatever the list returns should be readonly because writing to it would be a bug, and if somebody tries to, I want to halt and catch fire immediately, rather than wait for the bug to show up in some subtle way later.
Personally, I think this is better than any of the other answers:
static readonly IList<T> EmptyList = new T[0];
- Arrays implement
IList<T>
. - You cannot add to an array.
- You cannot assign to an element in an empty array (because there is none).
- This is, in my opinion, a lot simpler than
new List<T>().AsReadOnly()
. - You still get to return an
IList<T>
(if you want).
Incidentally, this is what Enumerable.Empty<T>()
actually uses under the hood, if I recall correctly. So theoretically you could even do (IList<T>)Enumerable.Empty<T>()
(though I see no good reason to do that).
这篇关于C#/ .NET equals for Java Collections。< T> emptyList()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!