質問

There are situations in which a method should be used with yield return, but not in others.

The question is that if a method with yield return is used to assign values ​​to a variable only one item is returned.

In this situation two methods will be needed, one for regular use and the other with yield return.

Is there some way to use the method with yield return outside a loop?

役に立ちましたか?

解決

Do you mean can you use yield return outside of a loop?

The answer is yes:

IEnumerable<string> GetStrings()
{
    yield return "foo";
    yield return "bar";
    yield return "baz";
}

...but this would be an unusual use case of yield return.

他のヒント

A method that uses yield return will return an IEnumerable and possibly something more specific like an IEnumerable<int>. If you are only interested in the first item, you can call:

int myInt = myYieldReturnMethod().First();
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top