C# IEnumerator/yield structure potentially bad?

前端 未结 11 1287
面向向阳花
面向向阳花 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:44

    As an aside - note that the IEnumerable approach is essentially what the LINQ providers (LINQ-to-SQL, LINQ-to-Entities) do for a living. The approach has advantages, as Jon says. However, there are definite problems too - in particular (for me) in terms of (the combination of) separation | abstraction.

    What I mean here is that:

    • in a MVC scenario (for example) you want your "get data" step to actually get data, so that you can test it works at the controller, not the view (without having to remember to call .ToList() etc)
    • you can't guarantee that another DAL implementation will be able to stream data (for example, a POX/WSE/SOAP call can't usually stream records); and you don't necessarily want to make the behaviour confusingly different (i.e. connection still open during iteration with one implementation, and closed for another)

    This ties in a bit with my thoughts here: Pragmatic LINQ.

    But I should stress - there are definitely times when the streaming is highly desirable. It isn't a simple "always vs never" thing...

提交回复
热议问题