return single instance object as IEnumerable

后端 未结 4 1711
夕颜
夕颜 2021-01-01 17:10

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:



        
4条回答
  •  甜味超标
    2021-01-01 17:35

    The best idiomatic way to do this is something like new[] { foo } which just creates a 1-element array of whatever type foo is declared to be.

    The one possible downside to this is that arrays aren't immutable, so somebody can cast your IEnumerable to a T[] and change the value in there. This is fairly unlikely, though, so I don't worry about it.

提交回复
热议问题