C# 是否可以使用屈服关键字返回值而不带循环?

C# 是否可以使用屈服关键字返回值而不带循环?,c#,.net,keyword,C#,.net,Keyword,我没有用于循环的,我想从一个方法返回5个整数。这可能吗?你能给我举个例子吗 我想一个接一个地返回值。我搜索了许多示例,但它们都显示了使用for循环返回yield值的方法,一些解释说,没有循环就不可能使用yield关键字。是的,绝对: public IEnumerable<int> GetValues() { yield return 10; yield return 5; yield return 15; yield return 23; yi

我没有用于循环的
,我想从一个方法返回5个整数。这可能吗?你能给我举个例子吗

我想一个接一个地返回值。我搜索了许多示例,但它们都显示了使用
for
循环返回
yield
值的方法,一些解释说,没有循环就不可能使用
yield
关键字。

是的,绝对:

public IEnumerable<int> GetValues()
{
    yield return 10;
    yield return 5;
    yield return 15;
    yield return 23;
    yield return 1;
}
如果您有更具体的要求,请告诉我们更多细节。

很好:

IEnumerable<int> myFunc()
{
    yield return 1;
    yield return 1;
    yield return 1;
    yield return 1;
    yield return 42;
}
IEnumerable myFunc()
{
收益率1;
收益率1;
收益率1;
收益率1;
收益率42;
}

e:比我快。。。雪上加霜的是,我注意到我的代码只返回四个整数。BRB,喝咖啡。

是的,您可以使用yield关键字返回多个值,而无需使用for循环,
下面是一个很好的例子:

// yield-example.cs
using System;
using System.Collections;
public class List
{
   IEnumerable <int> MyMethod()
    {

            yield return result1 ; 
            yield return result2 ; 
            yield return result5 ; 
            yield return result6; 

    }
}
//yield-example.cs
使用制度;
使用系统集合;
公共班级名单
{
IEnumerable MyMethod()
{
收益率结果1;
收益率结果2;
收益率结果5;
收益率结果6;
}
}
我想从这个方法中返回5个整数

您所需要的就是
out
参数:

 void MyMethod(out int a, out int b, out int c)  { a = 1; b = 2; c = 3; }

 int x, y, z;
 MyMethod(out x, out y, out z);

一次全部5个?或者一个接一个?—1。你没有研究过任何东西,你的需求解释得很差。请改进问题(例如,添加更多的上下文、真实世界的示例等)。这与我所看到的问题有很大不同,但仔细检查也同样有效。尽管在这一点上,@Jon Skeet在上面提出的仅返回数组的建议似乎具有相同的结果,但开销较小。数组版本更接近于屈服版本。
 void MyMethod(out int a, out int b, out int c)  { a = 1; b = 2; c = 3; }

 int x, y, z;
 MyMethod(out x, out y, out z);