C# IEnumerator/yield structure potentially bad?

前端 未结 11 1403
面向向阳花
面向向阳花 2021-02-01 02:47

Background: I\'ve got a bunch of strings that I\'m getting from a database, and I want to return them. Traditionally, it would be something like this:

public Li         


        
11条回答
  •  故里飘歌
    2021-02-01 03:35

    The only way this would cause problems is if the caller abuses the protocol of IEnumerable. The correct way to use it is to call Dispose on it when it is no longer needed.

    The implementation generated by yield return takes the Dispose call as a signal to execute any open finally blocks, which in your example will call Dispose on the objects you've created in the using statements.

    There are a number of language features (in particular foreach) which make it very easy to use IEnumerable correctly.

提交回复
热议问题