如何返回空值集合
我有一个字典,我想将其值返回给调用者,如下所示:
public ICollection<Event> GetSubscriptions()
{
return isLockDown ? Enumerable.Empty<Event> : subscriptionForwards.Values;
}
不幸的是,空可枚举类型与声明的返回类型不兼容。还有其他 BCL 设施吗?
ps 不,将三元的两个目标都转换为 (ICollection
不起作用
I have a dictionary whose values I'd like to return to a caller like this:
public ICollection<Event> GetSubscriptions()
{
return isLockDown ? Enumerable.Empty<Event> : subscriptionForwards.Values;
}
Unfortunately, the empty enumerable type is not compatible with the stated return type. Is there another BCL facility for this?
p.s. no, it does not work to cast both targets of the ternary as (ICollection<Event>)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于数组实现了
IList
,而IList
又扩展了ICollection
,因此您可以对空集合使用空数组。编辑:()。区别在于:
正如其他人指出的那样,您还可以返回 new List
new Event[0]
是只读的,调用者不能向其中添加元素(如果尝试,将会抛出异常)new List;()
是可变的,调用者可以向其中添加元素(尽管每个调用者都有自己的列表,因此其他调用者看不到更改)Since arrays implement
IList<T>
which in turn extendsICollection<T>
, you could use an empty array for your empty collection.Edit:
As others have pointed out, you could also return
new List<Event>()
. The difference will be:new Event[0]
is readonly, callers cannot add elements to it (an exception will be thrown if they try)new List<Event>()
is mutable, callers can add elements to it (although each caller gets its own list, so changes aren't visible to other callers)如果你真的仍然使用 Enumerable.Empty 你可以这样做:
If you really to still use Enumerable.Empty you could do this:
您可以使用它:
您需要添加此引用才能使其工作:
You could use this:
You need to add this reference in order for it to work:
您始终可以创建自己的空集合。至少构建只发生一次。
You could always create your own empty collection. At least the construction only happens once.