简体   繁体   English

在C#中创建IEnumerable匿名实例的语法是什么?

[英]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.

相关问题 什么是C#lambda的编译? 一个堆栈框架,一个匿名类型的实例,或? - What are C# lambda's compiled into? A stackframe, an instance of an anonymous type, or? C#匿名方法变量范围问题与IEnumerable <T> - C# Anonymous method variable scope problem with IEnumerable<T> 如何在C#抽象方法中指定可选的匿名可枚举参数 - how to specify optional anonymous ienumerable parameters in c# abstract method C#如何将IEnumerable匿名列表转换为数据表 - C# how to convert IEnumerable anonymous lists into data table 如何将C#中匿名类型的IEnumerable序列化为JavaScript Object? - How to serialize IEnumerable of Anonymous Type in C# to JavaScript Object? 在C#中将IEnumerable传递为参数,为什么这是正确的语法? 这是什么意思? - Passing an IEnumerable as an argument in C#, why is this the correct syntax? What does it mean? C#中的匿名方法是什么? - What are anonymous methods in C#? C#创建一个匿名类 - C# create a anonymous class 在C#中返回IEnumerable实例和yield return语句之间的确切区别是什么? - What is the exact difference between returning an IEnumerable instance and the yield return statement in C# 是否有在C#中创建匿名子类的语法? - Is there a syntax for creating an anonymous subclass in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM