Is yield useful outside of LINQ?

后端 未结 14 928
野性不改
野性不改 2020-12-24 06:44

When ever I think I can use the yield keyword, I take a step back and look at how it will impact my project. I always end up returning a collection instead of yeilding becau

14条回答
  •  萌比男神i
    2020-12-24 07:25

    I've used yeild in non-linq code things like this (assuming functions do not live in same class):

    public IEnumerable GetData()
    {
        foreach(String name in _someInternalDataCollection)
        {
            yield return name;
        }
    }
    
    ...
    
    public void DoSomething()
    {
        foreach(String value in GetData())
        {
            //... Do something with value that doesn't modify _someInternalDataCollection
        }
    }
    

    You have to be careful not to inadvertently modify the collection that your GetData() function is iterating over though, or it will throw an exception.

提交回复
热议问题