[英]What is the syntax to create an anonymous instance of IEnumerable in C#?
I have a function which takes an argument of IEnumerable. 我有一个函数接受IEnumerable的参数。 Let's call it: 我们称之为:
Iter(IEnumerable<string> list)
I have a single string that I would like to pass into the function. 我有一个想要传递给函数的字符串。 Is there a way to do it without actually creating some object that implements IEnumerable? 有没有一种方法,而无需实际创建实现IEnumerable的对象? It seems like I should be able to use a lambda instead, like : 看来我应该可以使用lambda代替,例如:
string thing1 = "Frank";
Iter( () => { yield return thing1 };);
To reiterate, no pun intended, I was wondering if there was a way to use an anonymous function/lambda so I don't have to create a instance of a container. 重申一下,没有双关语,我想知道是否有一种使用匿名函数/ lambda的方法,所以我不必创建容器的实例。
What about: 关于什么:
Iter(new [] {thing1});
Since your parameter is IEnumerable<string>
, you can pass an array or List<string>
. 由于您的参数是IEnumerable<string>
,因此您可以传递数组或List<string>
。
对于一个字符串,还有另一种方式:
Iter(Enumerable.Repeat<string>("thing1", 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.