返回单实例对象作为IEnumerable [英] return single instance object as IEnumerable

查看:166
本文介绍了返回单实例对象作为IEnumerable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类foo的实例,我想返回它作为IEnumerable。
我可以在不创建新列表等情况下进行。



可能类似如下:

  IEnumerable< foo> .fromInstance(foo)


解决方案

选项:




  • 创建集合类的实例,如数组或列表。这将是默认可变的,如果这是一个序列,你可以在你的API中提出,这将略有不利。您可以在此类集合周围创建 ReadOnlyCollection< T> 包装。

  • 编写自己的迭代器块根据Botz3000的回答

  • 如果你使用.NET 3.5,使用LINQ中的 Enumerable.Repeat(item,1)



这里最好的答案取决于用法。如果你只是需要这个调用另一个使用序列的方法,你知道它不会被修改,我可能会使用一个数组。例如,为了在某些其他序列上调用 Concat ,您可能需要:

  var wholeList = regularList.Concat(new [] {finalValue}); 

我相信 Concat 如果你需要将序列返回到其他代码,你就不需要返回序列了,但是没有其他任何方法可以看到对数组本身的引用。



<知道它可能会做什么,我可能会使用 Enumerable.Repeat


I have in instance of class foo and i want to return it as IEnumerable. Can i do it without creating a new list etc..

Perhaps something like the following:

IEnumerable<foo>.fromInstance(foo)

解决方案

Options:

  • Create an instance of a collection class, like an array or a list. This would be mutable by default, which would be slightly unhelpful if this is a sequence you want to be able to hand out in your API. You could create a ReadOnlyCollection<T> wrapper around such a collection though.
  • Write your own iterator block as per Botz3000's answer
  • Use Enumerable.Repeat(item, 1) from LINQ, if you're using .NET 3.5.

The best answer here depends on the usage. If you only need this to call another method which uses a sequence, and you know it won't be modified, I'd probably use an array. For example, in order to call Concat on some other sequence, you might want:

var wholeList = regularList.Concat(new[] { finalValue });

I have confidence that Concat isn't going to mutate the array, and nothing else will ever see the reference to the array itself.

If you need to return the sequence to some other code, and you don't know what it might do with it, I'd probably use Enumerable.Repeat.

这篇关于返回单实例对象作为IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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